gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:07:02 24 4
gpt4 key购买 nike

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

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

最佳答案

根据编辑 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'])

关于python - 如何从另一个 python 文件中调用需要命令行参数的 python 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33218968/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com