简体   繁体   English

如何将 argparse args 传递给导入的 python 脚本

[英]How to pass argparse args to python script that was imported

Say that I have a python script which can take in args假设我有一个可以接受 args 的 python 脚本

# testt.py
import argparse

def main(args):

    print(args.foo)
    print(args.bar)
    print(args.nee)

if __name__ == "__main__":

    parser = argparse.ArgumentParser(description='Test argument parser')

    parser.add_argument('-foo', type=str)
    parser.add_argument('-bar', type=int)
    parser.add_argument('-nee', type=bool)
    args = parser.parse_args()

    main(args)

But instead of running it from the command line, I want to run it from another Python program但不是从命令行运行它,我想从另一个 Python 程序运行它

import testt

How could I pass in the arg parameters?我怎么能传入 arg 参数?

You can write a class for the arguments:您可以为参数编写一个类:

import testt

class TesttArgs:
    def __init__(self, foo, bar, nee):
        self.foo = foo
        self.bar = bar
        self.nee = nee

testt.main(TesttArgs('foo', 2, False))

You could change the main() function in testt.py to do the parsing:您可以更改 testt.py 中的 main() 函数来进行解析:

# testt.py
import sys
import argparse

def main(args):

    parser = argparse.ArgumentParser(description='Test argument parser')

    parser.add_argument('-foo', type=str)
    parser.add_argument('-bar', type=int)
    parser.add_argument('-nee', type=lambda x: bool(int(x)))
    args = parser.parse_args(args)

    print(args.foo)
    print(args.bar)
    print(args.nee)

if __name__ == "__main__":

    main(sys.argv[1:])

Then pass sys.argv[1:] to testt.main(), from whatever program imports testt:然后将 sys.argv[1:] 传递给 testt.main(),从任何程序导入 testt:

# imp.py
import sys
import testt

if __name__ == "__main__":

    testt.main(sys.argv[1:])

One advantage is you no longer have to maintain a separate class when/if you change the command-line arguments you want to support.一个优点是当/如果您更改要支持的命令行参数时,您不再需要维护单独的类。

This draws heavily from: How to use python argparse with args other than sys.argv?这主要来自: How to use python argparse with args than sys.argv?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM