【问题标题】:How do you call a python file that requires a command line argument from within another python file?如何从另一个 python 文件中调用需要命令行参数的 python 文件?
【发布时间】:2016-01-18 01:39:05
【问题描述】:

例如,我有两个 python 文件,'test1.py''test2.py'。我想将import test2 转换为test1,这样当我运行test1 时,它也会运行test2

但是,为了正常运行,test2 需要输入参数。通常,当我从test1 外部运行test2 时,我只需在command line 中的文件调用之后键入参数。从test1 中调用test2 时,我该如何完成此操作?

【问题讨论】:

  • 在不知道test2 的结构的情况下,很难说。如果编写它的人将参数解析到单独的函数中和/或正确使用if __name__ == '__main__',您可能只是绕过它并直接注入您的参数。如果没有,您可能不得不摆弄sys.argv

标签: python import arguments call


【解决方案1】:

根据编辑 test2.py 的能力,有两种选择:

  1. (可编辑) 将 test2.py 内容打包到类中并在 init 中传递 args。

test1.py 文件中:

from test2 import test2class
t2c = test2class(neededArgumetGoHere)
t2c.main()

test2.py 文件中:

class test2class:
    def __init__(self, neededArgumetGoHere):
        self.myNeededArgument = neededArgumetGoHere

    def main(self):
        # do stuff here
        pass

# to run it from console like a simple script use
if __name__ == "__main__":
    t2c = test2class(neededArgumetGoHere)
    t2c.main()
  1. (无法编辑 test2.py) 将 test2.py 作为子进程运行。查看子进程docs 了解如何使用它的更多信息。

test1.py

from subprocess import call

call(['path/to/python','test2.py','neededArgumetGoHere'])

【讨论】:

    【解决方案2】:

    假设您可以定义自己的 test1 和 test2 并且可以使用 argparse(无论如何这是个好主意):

    使用 argparse 的好处是您可以让 test2 定义一大堆默认参数值,而 test1 不必担心。而且,在某种程度上,您有一个记录在案的 test2 调用接口。

    抄袭https://docs.python.org/2/howto/argparse.html

    test2.py

    import argparse
    
    def get_parser():
        "separate out parser definition in its own function"
        parser = argparse.ArgumentParser()
        parser.add_argument("square", help="display a square of a given number")
        return parser
    
    def main(args):
        "define a main as the test1=>test2 entry point"
        print (int(args.square)**2)
    
    if __name__ == '__main__':
        "standard test2 from command line call"
        parser = get_parser()
        args = parser.parse_args()
        main(args)
    

    audrey:explore jluc$ python test2.py 3

    9
    

    test1.py

    import test2
    import sys
    
    #ask test2 for its parser
    parser = test2.get_parser()
    
    try:
        #you can use sys.argv here if you want
        square = sys.argv[1]
    except IndexError:
        #argparse expects strings, not int
        square = "5"
    
    #parse the args for test2 based on what test1 wants to do
    #by default parse_args uses sys.argv, but you can provide a list
    #of strings yourself.
    args = parser.parse_args([square])
    
    #call test2 with the parsed args
    test2.main(args)
    

    audrey:explore jluc$ python test1.py 6

    36
    

    audrey:explore jluc$ python test1.py

    25
    

    【讨论】:

      【解决方案3】:

      您可以使用 subprocess 模块中的 call 或 popen 方法。

      from subprocess import call, Popen
      
      Call(file, args)
      Popen(file args)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-30
        相关资源
        最近更新 更多