例如,我有两个 python 文件,'test1.py'
和 'test2.py'
。我想将 import test2
导入 test1
,这样当我运行 test1
时,它也会运行 test2
。
但是,为了正常运行,test2
需要一个输入参数。通常,当我从 test1
外部运行 test2
时,我只是在 命令行
中调用文件后键入参数。从 test1
中调用 test2
时如何完成此操作?
最佳答案
根据编辑 test2.py 的能力,有两种选择:
- (可编辑) 将 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()
- (无法编辑 test2.py) 将 test2.py 作为子进程运行。检查子进程 docs有关如何使用它的更多信息。
test1.py
from subprocess import call
call(['path/to/python','test2.py','neededArgumetGoHere'])
关于python - 如何从另一个 python 文件中调用需要命令行参数的 python 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33218968/