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

标签 python import arguments call

例如,我有两个 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/

相关文章:

python - 删除_Widget 不起作用

c++ - 将类对象传递给函数(可能通过指针而不是引用)C++

ssh - 如何强制 ssh 从命令行接受新的主机指纹?

css - LESS CSS - Mixin Arguments 和 Nth-Child - 没有循环

python - 旋转列表中的值 [Python]

python - 打开 2 个文件并将它们分配给 Python 3 中的 2 个集合

c++ - 如何在 Visual Studio 2010 c++ 项目中使用 System.Net 命名空间?

haskell - 导入 type level naturals 的 * 运算符

python - 使用 Python 抓取数据属性时遇到问题

java - 我可以删除任何隐式导入的 Java 库吗?