简体   繁体   English

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

[英]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)

exec_file documentation exec_file 文档

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

相关问题 我如何在较低的目录中运行另一个 Python 文件 - How do i run another Python file in a lower directory 如何在pylab中运行一个python文件,该文件会执行另一个python文件? - How do I run a python file in pylab, which executes another python file? 如何使用 kivy 中的屏幕管理器在另一个 python 文件中运行 python 文件 - How do I run a python file inside another python file with Screen manager in kivy 如何在另一个python文件中运行python文件? - How do I run my python file within another python file? 如何在与另一个python文件不同的目录中运行python文件? - How do I run a python file in a different directory from another python file? 如何运行带有参数作为来自另一个 python 文件的变量的 python 文件? - How do I run a python file with arguments as variables from another python file? 你如何让 python 文件运行另一个 python 文件 - How do you make python file run another python file 如何从另一个python文件运行一个python文件? - How do you run a python file from another python file? 如何在另一个 python 文件中运行 python 文件? - How can I run a python file inside another python file? 如何在另一个进程中运行一些python代码? - How do I run some python code in another process?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM