如何通过子进程从ARGPARSE提供ARG的ARG到外部程序调用

发布于 2025-02-09 22:45:48 字数 1063 浏览 1 评论 0原文

在任务中,我需要调用通过Python在终端运行的外部程序。该外部程序具有许多位置和可选论点。

这是开发的示例代码SOFAR:

def multi_character_parameter():

    parser = argparse.ArgumentParser()

    parser.add_argument('b',
                        help="Execute tests with browser 'firefox' or 'chrome', or 'ALL")
    parser.add_argument('C', help="Execute tests in cloud 'aws' or 'azure'")
    parser.add_argument(
        'c', help="Clear output and temp directory before executing tests")
    parser.add_argument('d', help="Check syntax for test data")
    parser.add_argument("--upper-case", default=False, action="store_true")
...
args = parser.parse_args()

def my_external_program():
 subprocess.call(["external_program"])

有人可以建议:

  1. 如何将这些ARG提供给通过子过程调用的 external_program

即,在运行python script.py some_args时,这些some_args将提供给external_program以执行为external_program some_args some_args代码>。

  1. 如果需要在代码的其他部分中使用args,则更好的方法是构建代码的更好方法。

In a task, I need to call an external program that run on terminal via python. This external program has lots of positional and optional arguments.

Here is the sample code developed sofar:

def multi_character_parameter():

    parser = argparse.ArgumentParser()

    parser.add_argument('b',
                        help="Execute tests with browser 'firefox' or 'chrome', or 'ALL")
    parser.add_argument('C', help="Execute tests in cloud 'aws' or 'azure'")
    parser.add_argument(
        'c', help="Clear output and temp directory before executing tests")
    parser.add_argument('d', help="Check syntax for test data")
    parser.add_argument("--upper-case", default=False, action="store_true")
...
args = parser.parse_args()

def my_external_program():
 subprocess.call(["external_program"])

Could someone please suggest:

  1. How to supply these args to the external_program called via subprocess.

i.e. upon running say python script.py some_args, these some_args will be supplied to the external_program function for execution as external_program some_args.

  1. What would be the better way to structure the code if the args specified in the code needs to be used at other parts of the code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

转身泪倾城 2025-02-16 22:45:48

设置变量args后,您可以使用点表示法访问任何参数。

我已经编辑了您的代码以证明这一点:

#!/usr/bin/env python3
 
import argparse
import subprocess

def multi_character_parameter():

    parser = argparse.ArgumentParser()

    parser.add_argument('--b',
                        help="Execute tests with browser 'firefox' or 'chrome', or 'ALL",
                        required=False,
                        default=False)
    parser.add_argument('--C', help="Execute tests in cloud 'aws' or 'azure'",
        required=False, default=False)   
    parser.add_argument(
        '--c', help="Clear output and temp directory before executing tests",
        required=False, default=False)
    parser.add_argument('--d', help="Check syntax for test data", required=False, default=False)
    parser.add_argument("--upper-case", action="store_true", required=False, default=False)
    args = parser.parse_args()
    return args

def my_external_program(args):
    print(args)
    b = str(args.b)
    C = str(args.C)
    c = str(args.c)
    d = str(args.d)
    upper_case = str(args.upper_case)
    subprocess.call(["echo", b,C,c,d,upper_case ])


if __name__ == "__main__":
    args = multi_character_parameter()
    my_external_program(multi_character_parameter())

现在将其运行chmod +x test.py

./ test.py

显示了stdout以显示对ARGS的访问(外部程序被用作echo作为程序:

Namespace(b=False, C=False, c=False, d=False, upper_case=False)
False False False False False

Once you set the variable args, you can access any of the arguments using dot notation.

I have edited your code to demonstrate this:

#!/usr/bin/env python3
 
import argparse
import subprocess

def multi_character_parameter():

    parser = argparse.ArgumentParser()

    parser.add_argument('--b',
                        help="Execute tests with browser 'firefox' or 'chrome', or 'ALL",
                        required=False,
                        default=False)
    parser.add_argument('--C', help="Execute tests in cloud 'aws' or 'azure'",
        required=False, default=False)   
    parser.add_argument(
        '--c', help="Clear output and temp directory before executing tests",
        required=False, default=False)
    parser.add_argument('--d', help="Check syntax for test data", required=False, default=False)
    parser.add_argument("--upper-case", action="store_true", required=False, default=False)
    args = parser.parse_args()
    return args

def my_external_program(args):
    print(args)
    b = str(args.b)
    C = str(args.C)
    c = str(args.c)
    d = str(args.d)
    upper_case = str(args.upper_case)
    subprocess.call(["echo", b,C,c,d,upper_case ])


if __name__ == "__main__":
    args = multi_character_parameter()
    my_external_program(multi_character_parameter())

Now to run it chmod +x test.py

./test.py

The stdout is presented to show access to the args (the external program was subbed out for echo as the program:

Namespace(b=False, C=False, c=False, d=False, upper_case=False)
False False False False False

∞梦里开花 2025-02-16 22:45:48

如果您只想通过所有参数:

import sys

subprocess.call(["external_program"] + sys.argv[1:])

将所有参数传递给脚本(第一个参数,这是脚本的名称),然后将它们附加到您已经提供的参数,外部程序的名称 - 和可能是按预期工作的。

因此,如果您要运行python your_script.py 1 2 3 4(与指定的参数要求匹配),它将调用external_program 1 2 3 4

更一般的答案是,您应该只为subprocess.call提供一个参数列表,如 subprocess.call.call - “ args应该是程序的顺序,参数,否则单个字符串或类似路径的对象。”

由于您没有提供有关您所追求的映射的准确信息,或者对脚本的参数如何转化为外部程序的参数,因此不可能更具体地说明 - 除了说您需要构建一系列参数通话。

If you just want to literally pass all the arguments:

import sys

subprocess.call(["external_program"] + sys.argv[1:])

This takes all the arguments passed to the script (except the first, which is the script's name) and just appends them to the argument you already provided, the name of the external program - and probably works as expected.

So, if you were to run python your_script.py 1 2 3 4 (which matches your specified argument requirements), it would call external_program 1 2 3 4.

The more general answer is that you should just provide a list of arguments to subprocess.call, as described in the documentation for subprocess.call - "args should be a sequence of program arguments or else a single string or path-like object."

Since you provide no information on exactly what mapping you're after, or how the arguments to your script translate to arguments for the external program, it's not possible to be a lot more specific - other than saying you need to construct a sequence of arguments to pass to the call.

瑾兮 2025-02-16 22:45:48

如果要限制或限制传递给external_program的参数,则可以做这样的事情

allowed_args = ['--upper-case', 'b', 'c', 'C', 'd']
subprocess.run(['external_program'] + list(set(sys.argv).intersection(allowed_args)))

If you want to limit or restrict the arguments passed to external_program you can do something like this

allowed_args = ['--upper-case', 'b', 'c', 'C', 'd']
subprocess.run(['external_program'] + list(set(sys.argv).intersection(allowed_args)))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文