【发布时间】:2018-08-03 10:15:46
【问题描述】:
我想在另一个 Python 脚本 (run_python_script.py) 中启动一个 Python 脚本(我将其称为 test.py)。为此,我使用如下所示的子进程命令:https://stackoverflow.com/a/18422264。
那就是 run_python_script.py :
import subprocess
import sys
import io
import time
def runPython(filename, filename_log="log.txt"):
with io.open(filename_log, 'wb') as writer, io.open(filename_log, 'rb', 1) as reader:
process = subprocess.Popen("python {}".format(filename), stdout=writer)
while process.poll() is None:
sys.stdout.write(reader.read().decode("utf-8"))
time.sleep(0.5)
# Read the remaining
sys.stdout.write(reader.read().decode("utf-8"))
runPython("test.py")
这是 test.py :
import time
sleep_time = 0.0001
start_time = time.time()
for i in range(10000):
print(i)
time.sleep(sleep_time)
print(time.time() - start_time)
在此设置中,实时输出有效,但如果 sleep_time(在 test.py 中)过大,例如 sleep_time = 1。 run_python_script.py 仅在 test.py 完成后输出。
我将 time.sleep(sleep_time) 替换为其他函数,每个需要很长时间的函数都会破坏实时输出。
当然 test.py 只是一个例子。我想用其他方法,结果是一样的。
【问题讨论】:
标签: python python-3.x subprocess