我正在编写需要打开另一个脚本的脚本,但继续运行主脚本,以便两个脚本同时运行。
我试过 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/