简体   繁体   English

如何从另一个 Python3 文件运行整个 Python3 文件?

[英]How can I run an entire Python3 file from another Python3 file?

I have 2.py files: test.py and test2.py我有 2.py 文件:test.py 和 test2.py

test.py:测试.py:

import test2
print("This is test.py")

test2.py:测试2.py:

print("This is test2.py")

When I run test.py, I get:当我运行 test.py 时,我得到:

This is test.py

How can I print "This is test2.py" by running test2.py from test.py?如何通过从 test.py 运行 test2.py 来打印“This is test2.py”?

Solution found:找到的解决方案:

test.py:测试.py:

print("This is test.py")
exec(open("test2.py").read())

test2.py:测试2.py:

if __name__ == '__main__':
    print("This is test2.py")

Output: Output:

This is test.py
This is test2.py

I think that there are many ways to do, but I think that subproccess will help you:我认为有很多方法可以做,但我认为 subprocess 会帮助你:

subprocess.run(["python", "path/to/test2.py"])

This will execute a shell command to open python and then tell him(python) to open and execute test2.py.这将执行一个 shell 命令打开 python 然后告诉他(python)打开并执行 test2.py。 Here is the documentation: https://docs.python.org/3/library/subprocess.html这是文档: https://docs.python.org/3/library/subprocess.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM