[英]How do I run another file in python?
So I know how to write in a file or read a file but how do I RUN another file?所以我知道如何写入文件或读取文件,但如何运行另一个文件?
for example in a file I have this: a = 1
print(a)
例如在一个文件中我有这个: a = 1
print(a)
How do I run this using another file?如何使用另一个文件运行它?
file_path = "<path_to_your_python_file>"
using subprocess
standard lib使用subprocess
标准库
import subprocess
subprocess.call(["python3", file_path])
or using os
standard lib或使用os
标准库
import os
os.system(f"python3 {file_path}")
or extract python code
from the file and run it inside your script:或从文件中提取python code
并在脚本中运行它:
with open(file_path, "r+", encoding="utf-8") as another_file:
python_code = another_file.read()
# running the code inside the file
exec(python_code)
exec
is a function that runs python strings exactly how python interpreter
runs python files
. exec
是一个运行 python 的 function 字符串, python interpreter
运行python files
的方式完全相同。
IN ADDITION此外
if you want to see the output of the python file:如果要查看 python 文件的 output :
import subprocess
p = subprocess.Popen(
["python3", file_path],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
err, output = p.communicate()
print(err)
print(output)
EXTRA额外的
for people who are using python2
:对于使用python2
的人:
execfile(file_path)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.