如何使用 args

如何解决如何使用 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

我现在必须创建一个脚本来运行上面的所有脚本,我什至不知道从哪里开始。我已经看到了 subprocesssys.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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?