我如何 运行 python 中的另一个文件?

How do I run another file in python?

所以我知道如何在文件中写入或读取文件,但我如何 运行 另一个文件?

例如在一个文件中我有这个: a = 1 print(a)

如何使用另一个文件运行?

file_path = "<path_to_your_python_file>"

使用 subprocess 标准库

import subprocess
subprocess.call(["python3", file_path])

或使用os标准库

import os
os.system(f"python3 {file_path}")

或从文件中提取 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 是一个函数,它 运行s python 准确地字符串 python interpreter 运行s python files.

另外

如果您想查看 python 文件的输出:

import subprocess
p = subprocess.Popen(
  ["python3", file_path], 
  stdout=subprocess.PIPE, 
  stderr=subprocess.PIPE
)
err, output = p.communicate()
print(err)
print(output)

额外

对于正在使用 python2 的人:

execfile(file_path)

exec_file documentation