2 回答
TA贡献1804条经验 获得超7个赞
使 argparse 接受一个位置参数(文件名或字符串)和一个标志 (-i)。如果存在标志,则将参数视为文件。查看argparse 教程以获取更多信息。我修改了示例以满足您的需要。
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("inp", help="input string or input file")
parser.add_argument("-i", "--treat-as-file", action="store_true",
help="reads from file if specified")
args = parser.parse_args()
if args.treat_as_file:
print("Treating {} as input file".format(args.inp))
else:
print("Treating {} as the input".format(args.inp))
输出:
/tmp $ python test.py abcde
Treating abcde as the input
/tmp $ python test.py -i abcde
Treating abcde as input file
TA贡献1846条经验 获得超7个赞
要处理命令行字符串,您可以使用sys.argv
,它是输入命令行的所有参数的列表。
main.py:
import sys print(sys.argv)
在 CLI 中运行以下行
>> python main.py foo bar "hello world"
会输出:
['main.py', 'foo', 'bar', 'hello world']
添加回答
举报