如何在另一个python文件中调用需要命令行参数的python文件?

Sol*_*mon 8 python import arguments call

例如,我有两个python文件,'test1.py''test2.py'.我想import test2进入test1,所以当我跑步时test1,它也会运行test2.

但是,为了正常运行,test2需要输入参数.通常当我test2从外面运行时test1,我只需在文件调用后输入参数command line.test2从内部打电话时如何实现这一目标test1

小智 5

根据编辑 test2.py 的能力,有两个选项:

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

test1.py文件中:

from test2 import test2class
t2c = test2class(neededArgumetGoHere)
t2c.main()
Run Code Online (Sandbox Code Playgroud)

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()
Run Code Online (Sandbox Code Playgroud)
  1. (无法编辑 test2.py)将test2.py 作为子进程运行。检查子流程文档以获取更多信息如何使用它。

测试1.py

from subprocess import call

call(['path/to/python','test2.py','neededArgumetGoHere'])
Run Code Online (Sandbox Code Playgroud)