如何解决如何使用 args
我还是 Python 新手,我有多个脚本,我必须将参数传递给它们才能运行。它们都设置为在命令行中运行,例如:
python script1 -c config/config_file1.json -m import
python script2 -c config/config_file1.json -cl config/config_file2.json
python script3 -c config/config_file3.json -d name
我现在必须创建一个脚本来运行上面的所有脚本,我什至不知道从哪里开始。我已经看到了 subprocess 或 sys.argv 的建议,但我不知道这种情况的最佳方法是什么。我所需要的只是能够运行主脚本来运行所有其他 3 个脚本,并知道处理我需要传递给它们的所有参数的最佳方法。任何建议将不胜感激。
解决方法
如果脚本的参数是静态的,则:
import subprocess
# This is like running `python script1 -c config/config_file1.json -m import` and your other commands
subprocess.call(["python","script1","-c","config/config_file1.json","-m","import"])
subprocess.call(["python","script2","-cl","config/config_file2.json"])
subprocess.call(["python","script3","config/config_file3.json","-d","name"])
如果你每次都需要传入不同的参数,那么你可以从 input()
或 argparse
库中获取它们(在这种情况下个人更喜欢 argparse
):
import argparse
import subprocess
def get_args():
parser = argparse.ArgumentParser()
# The add_argument method takes this pattern: ("--flag","-abreviated-flag",dest="variable_to_store_input",help="Help message to display for partcular argument")
parser.add_argument("--name","-n",dest="name",help="Name to enter: --name Bill,OR -n Bill")
parser.add_argument("--age","-a",dest="age",help="Age to enter: --age 21,OR -a 21")
# Add as many arguments as you need following this format.
args = parser.parse_args() # Collect and parse the inputed arguments
# Make sure needed arguments are there
if not args.age:
parser.error("No age specified! Use --help for more info.")
if not args.name:
parser.error("No name specified! Use --help for more info")
return args # If this line is reached,all of the arguments are filled
arguments = get_args() # Gets the arguments
name = arguments.name
age = arguments.age
# This is just like running the command: `python script1 --name <some-name> --age <some-age>`
subprocess.call(["python","--name",name,"--age",age])
# You can also store the command:
command = ["python",age]
subprocess.call(command)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。