python - 从 Python 脚本如何运行其他 Python 脚本?

标签 python windows bash shell ubuntu

在我的主要Python脚本中,我想调用另一个python脚本来运行,如下:python2 ~/script_location/my_side_script.py \ --input-dir folder1/in_folder \ --output-dir folder1/out_folder/ \ --image-ext jpg \在我的 Python 脚本中,我究竟该怎么做?
我将同时使用 Windows 和 Ubuntu,但主要是后者。理想情况下希望能够在两者上都做。

最佳答案

您可以在主文件中导入脚本。

假设你有两个文件:myscript.py 和 main.py

# myscript.py
print('this is my script!')
# main.py
print('this is my main file')
import myscript
print('end')

运行 main.py 时的输出将会:

this is my main file
this is my script
end

编辑:如果您真的只是想调用python2 my_side_script.py --options asdf ,您可以使用 subprocess python 模块:
import subprocess

stdout = subprocess.check_output(['python2', 'my_side_script.py', '--options', 'asdf'])

print(stdout)      # will print any output from your sidescript

关于python - 从 Python 脚本如何运行其他 Python 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54335876/

相关文章:

bash - 如何在 Bash 中的另一个函数中定义一个函数?

python matplotlib : unable to call FuncAnimation from inside a function

python - 当我以面向对象的方式使用matplotlib编程时,是否可以在jupyter笔记本中自动完成代码?

python - 试图从 scipy powerlaw fit 中获得合理的值(value)

windows - 使用Robot Framework扫描本地主机上的打开端口

c++ - 需要 GDI 编程指南

c# - 在 Windows 中捕获 http/https 请求

python - 在 python 中映射嵌套字典

linux - 如何在 bash 中添加列索引

linux - 是否可以从 bash 脚本中设置超时?