使用sys.argv argparse致电main

发布于 2025-02-11 03:43:21 字数 885 浏览 0 评论 0原文

我有一个主函数,该功能使用argparse从sys.argv中获取ARG:

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-arg1', '--argument1', type=str, required=True)
    parser.add_argument('-arg2', '--argument2', type=str, required=True)
    args = parser.parse_args()

主函数从另一个模块称为mod.main()。 当我打印传递给主要函数的内容时,args是:[' - arg1','val1','-arg2','val2'],这是正确的参数列表。

但是,当我运行时,似乎Argparse的ARGS似乎未正确传递。

['-arg1', 'val1', '-arg2', 'val2']
usage: -arg1 [-h] -arg2 ARG2 -arg1 ARG1
-arg1: error: the following arguments are required: -arg1

问题是我没有运行run_module.py,该py从命令行调用module_to_to_call.main(),而是将其传递给Spark-Supparmit以在EMR上运行。

"HadoopJarStep": {
                "Args": [
                    "spark-submit",..., "run_module.py", "module_to_call", "-arg1", "val1", "-arg2", "val2",...

I have a main function which takes args from sys.argv using argparse:

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-arg1', '--argument1', type=str, required=True)
    parser.add_argument('-arg2', '--argument2', type=str, required=True)
    args = parser.parse_args()

The main function is called from another module as mod.main().
When i print what is passed to the main function the args are: ['-arg1', 'val1', '-arg2', 'val2'] which is the correct list of arguments.

However, when i run it it seems that the args are not passed correctly with argparse.

['-arg1', 'val1', '-arg2', 'val2']
usage: -arg1 [-h] -arg2 ARG2 -arg1 ARG1
-arg1: error: the following arguments are required: -arg1

The issue is that i am not running the run_module.py which calls the module_to_call.main() from the command line but passing it as args to spark-submit in order to run it on EMR.

"HadoopJarStep": {
                "Args": [
                    "spark-submit",..., "run_module.py", "module_to_call", "-arg1", "val1", "-arg2", "val2",...

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

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

发布评论

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

评论(1

话少心凉 2025-02-18 03:43:21

这是一个最小的示例,

#!/usr/bin/env python
# argparse_example.py
import sys
import argparse

def main():
    print(sys.argv)
    parser = argparse.ArgumentParser()
    parser.add_argument('-arg1', '--argument1', type=str, required=True)
    parser.add_argument('-arg2', '--argument2', type=str, required=True)
    args = parser.parse_args()
    print(args)

if __name__ == "__main__":
    main()

您可以使用它运行

python argparse_example.py -arg1 val1 -arg2 val2

并进行

['argparse_example.py', '-arg1', 'val1', '-arg2', 'val2']
Namespace(argument1='val1', argument2='val2')

或运行它,而无需参数

python argparse_example.py

以获取帮助消息:

['argg.py']
usage: argg.py [-h] -arg1 ARGUMENT1 -arg2 ARGUMENT2
argg.py: error: the following arguments are required: -arg1/--argument1, -arg2/--argument2

Update

从OP的评论中,我意识到sys.argv >在函数main()函数的途中被某些封底的代码被弄脏,第一个参数被切断了。

参数列表[' - arg1','val1','-arg2','val2']不是,因为它缺少> sys.argv [0] - 从命令行调用Python脚本的名称。由于argparse processes sys.argv [1:],它无法找到' - arg1',因此失败了错误。

在这种情况下,您可以将一个虚拟元素添加到sys.argv以确保-arg1将在代码处时传递到argparse作为模块运行。

#!/usr/bin/env python
# argparse_example.py
import sys
import argparse

def main():
    print(sys.argv)
    if __name__ != "__main__":
        # we are running as a module so add a dummy argument
        sys.argv = ['argparse_example.py'] + sys.argv
    parser = argparse.ArgumentParser()
    parser.add_argument('-arg1', '--argument1', type=str, required=True)
    parser.add_argument('-arg2', '--argument2', type=str, required=True)
    args = parser.parse_args()
    print(args)

if __name__ == "__main__":
    main()

您可以使用以下包裹的代码对其进行测试

#!/usr/bin/env python
# runner.py
import sys
import argparse_example

if __name__ == "__main__":
    sys.argv = sys.argv[1:]
    argparse_example.main()

,并从命令行调用它:

python runner.py -arg1 val1 -arg2 val2

即使sys.argv,结果也应与直接从命令行调用argparse_example时相同。将缺少第一个元素:

['-arg1', 'val1', '-arg2', 'val2']
Namespace(argument1='val1', argument2='val2')

Here is a minimal example for you

#!/usr/bin/env python
# argparse_example.py
import sys
import argparse

def main():
    print(sys.argv)
    parser = argparse.ArgumentParser()
    parser.add_argument('-arg1', '--argument1', type=str, required=True)
    parser.add_argument('-arg2', '--argument2', type=str, required=True)
    args = parser.parse_args()
    print(args)

if __name__ == "__main__":
    main()

You can run it with

python argparse_example.py -arg1 val1 -arg2 val2

And get

['argparse_example.py', '-arg1', 'val1', '-arg2', 'val2']
Namespace(argument1='val1', argument2='val2')

Or run it without arguments

python argparse_example.py

to get the help message:

['argg.py']
usage: argg.py [-h] -arg1 ARGUMENT1 -arg2 ARGUMENT2
argg.py: error: the following arguments are required: -arg1/--argument1, -arg2/--argument2

UPDATE

From comments by the OP I realize that sys.argv got mangled on the way to function main() by some enveloping code and the first argument got cut off.

The argument list ['-arg1', 'val1', '-arg2', 'val2'] is not the correct list of arguments as it is missing sys.argv[0] — the name of the python script being called from the command line. As argparse processes sys.argv[1:], it is unable to find '-arg1' and therefore fails with an error.

In this case you can add a dummy element to sys.argv to make sure that -arg1 will be passed to argparse when your code is being run as a module.

#!/usr/bin/env python
# argparse_example.py
import sys
import argparse

def main():
    print(sys.argv)
    if __name__ != "__main__":
        # we are running as a module so add a dummy argument
        sys.argv = ['argparse_example.py'] + sys.argv
    parser = argparse.ArgumentParser()
    parser.add_argument('-arg1', '--argument1', type=str, required=True)
    parser.add_argument('-arg2', '--argument2', type=str, required=True)
    args = parser.parse_args()
    print(args)

if __name__ == "__main__":
    main()

You can test it with the following enveloping code

#!/usr/bin/env python
# runner.py
import sys
import argparse_example

if __name__ == "__main__":
    sys.argv = sys.argv[1:]
    argparse_example.main()

And call it from the command line like this:

python runner.py -arg1 val1 -arg2 val2

The result should be the same as when calling argparse_example directly from the command line, even though sys.argv will be missing the first element:

['-arg1', 'val1', '-arg2', 'val2']
Namespace(argument1='val1', argument2='val2')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文