【发布时间】:2021-10-20 10:34:15
【问题描述】:
我正在编写一个脚本来根据参数调用不同的 python 脚本。 Argparser 不允许我更改为只给出 1。
目前我正在使用带有 -option1 的 argparser,但想作为 $script.py 1 运行
当前运行方式
$script.py -option1
想用
$script.py 1
我的代码:-
import argparse
def main():
parser = argparse.ArgumentParser()
#parser.add_argument('1', action='store_true')
parser.add_argument('-option1', default=None, action='store_true', help="This runs hello-1.py") # want to use '1' insted of '--option1'
parser.add_argument('-option2', action='store_true', default=None, help="This runs hello-2.py")
parser.add_argument('-option3', action='store_true', default=None, help="This runs hello-3.py")
#parser.add_argument('-l', action='store_true')
args = parser.parse_args()
if args.option1: #want to use args.1 here but won't allow
with open("hello-1.py", "r") as file:
exec(file.read())
elif args.option2:
with open("hello-2.py", "r") as file:
exec(file.read())
elif args.option3:
with open("hello-3.py", "r") as file:
exec(file.read())
else:
print("Invalid argument")
file.close()
return args
if __name__ == '__main__':
main()
#if args.l:
# print("List files within config")
请推荐
【问题讨论】:
-
你想要的实际上是不可能的。
1是一个 positional 参数,而不是一个选项。您可以将其设为可选,但不能使其在参数列表中的位置发生变化。如果你先定义它,它必须是第一个位置参数。 -
store_true与positional没有意义。 -
使用
store_true时不要设置default。该操作将默认设置为False,使用时设置为True。
标签: python python-3.x command-line-arguments argparse