python - 当我使用 os.system() 在 Python 中打开一个 .py 文件时,它会立即自动关闭它。我该如何解决?

标签 python os.system

我正在编写需要打开另一个脚本的脚本,但继续运行主脚本,以便两个脚本同时运行。

我试过 execfile() 但文件打不开。当我使用 os.system(somefile.py) 时,它通过控制台成功打开了 .py 文件,但立即将其关闭。是否有替代方案,以便我可以在主 python 脚本中运行 python 脚本,但同时运行两个进程而不会相互冲突?

这是我测试过的示例代码:

import os
file_path = 'C:\\Users\\Tyler\\Documents\\Multitask Bot\\somefile.py'

def main():
    os.system(file_path)

if __name__ == '__main__':
    main()

最佳答案

execfile()os.system() 将阻塞父进程,直到子进程退出。使用 subprocess.Popen(),例如

import subprocess, time
file_path = 'C:\\Users\\Tyler\\Documents\\Multitask Bot\\somefile.py'

def main():
    child = subprocess.Popen(['python', file_path])
    while child.poll() is None:
        print "parent: child (pid = %d) is still running" % child.pid
        # do parent stuff
        time.sleep(1)
    print "parent: child has terminated, returncode = %d" % child.returncode

if __name__ == '__main__':
    main()

这只是处理它的一种方法。您可能希望从 child 那里收集标准输出和/或标准错误,并可能将数据发送到 child 的标准输入。阅读子流程模块。

关于python - 当我使用 os.system() 在 Python 中打开一个 .py 文件时,它会立即自动关闭它。我该如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11679549/

相关文章:

python - 在 Python 中查找目录中的特定路径

python - 在 Python 中停止进程

python - os.system() 在 Ubuntu 中与 "strings"命令一起使用时不起作用

python - Eager Execution 函数的输入不能是 Keras 符号张量

Python:简单 OLS super 词典

python - 为什么 Visual Studio Code 无法识别我的 WSL bash python?

python - 检测并处理通过 Python 中的 os.system 调用生成的 LaTeX 警告/错误

python - Matplotlib set_data xdata 和 ydata must be same length 错误

python - 如何检测十进制列是否应转换为整数或 double ?

python - 在 Win10 上从 Python 备份 Postgres