首页 > 解决方案 > 如何启动、停止和从另一个 python 程序获取输出

问题描述

我希望能够启动、停止和获取另一个 python 程序的控制台输出。我不想在当前程序中运行它,我希望它们作为两个单独的实例运行。

这两个文件都在同一个目录中。

我已经看到了有关如何获取另一个 python 程序的控制台输出以及如何启动和停止它的指南,但我无法找到两者的指南。

我还应该注意,我想要输出的文件是一个 .pyw 文件。

谢谢。

编辑:不是重复的,它不是那么简单......

编辑2:

这是我的尝试

main.py

import subprocess

p = subprocess.Popen(['python', 'sub.py'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# continue with your code then terminate the child
with p.stdout:
    for line in iter(p.stdout.readline, b''):
        print(line)
p.wait()

sub.py

import time

for i in range(100):
    print(i)
    time.sleep(1)

它有点工作,但它打印出来就像

b'0\r\n' b'1\r\n' b'2\r\n' b'3\r\n' b'4\r\n'

编辑3:

import subprocess

p = subprocess.Popen(['python', 'sub.py'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
with p.stdout:
    for line in iter(p.stdout.readline, b''):
        print(line.decode("utf-8").replace("\r\n", ""))
p.wait()

这是最好的方法吗?

但是,我仍然遇到问题。我想完全单独运行程序,所以我应该能够同时运行main.py程序中的其他代码,但这不起作用。

import subprocess
import time


def get_output():
    p = subprocess.Popen(['python', 'sub.py'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    with p.stdout:
        for line in iter(p.stdout.readline, b''):
            print(line.decode("utf-8").replace("\r\n", ""))
    p.wait()


def print_stuff():
    for i in range(100):
        print("." + str(i))
        time.sleep(1)


if __name__ == "__main__":
    get_output()
    print_stuff()
import time


def main():
    for i in range(100):
        print(i)
        time.sleep(1)


if __name__ == "__main__":
    main()

EDIT4: 这是我同时运行它们的尝试

import subprocess
import asyncio


async def get_output():
    p = subprocess.Popen(['python', 'sub.py', 'watch', 'ls'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    with p.stdout:
        for line in iter(p.stdout.readline, b''):
            print(line.decode("utf-8").replace("\r\n", ""))
    p.wait()


async def print_stuff():
    for i in range(100):
        print("." + str(i))
        await asyncio.sleep(1)


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.gather(
        print_stuff(),
        get_output()
    ))
    loop.close()
import asyncio


async def main():
    for i in range(100):
        print(i)
        await asyncio.sleep(1)

if __name__ == "__main__":
    asyncio.run(main())

预期的输出是

.0 0 .1 1 .2 2 ...

但输出是

.0 0 1 2 3 4 5 ...

EDIT5: 我认为问题在于subprocess.Popen持有该程序,所以我认为我需要使用asyncio.create_subprocess_execm 但我无法弄清楚如何让它工作。

标签: python

解决方案


当我问一个类似的问题时,我是这样做的。我还需要在打印后立即输出,而不是等待缓冲区填满。

子进程

from time import sleep

# Dummy child process for popen demonstration
# Print "sleeping" at 1-sec intervals, then a "QUIT" message.

for _ in range(5):
    print(_, "sleeping")
    sleep(1)

print("Child process finishes")

父进程

import subprocess
import time

# Turn off output buffering in Python;
#   we need each output as soon as it's printed.
environ["PYTHONUNBUFFERED"] = "1"

# Locate the child's source file -- YOU can use a local path.
branch_root = environ["PYTHONPATH"]
cmd = ["/usr/bin/python3", branch_root + "popen_child.py"]

# Start the child process, opening a pipe from its stdout
# Include stderr under stdout.
test_proc = subprocess.Popen(
    cmd,
    universal_newlines=True,
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
)

print(time.time(), "START")

# Catch and print the output as it's generated.
for out_data in iter(test_proc.stdout.readline, ""):
    print(time.time(), out_data, end="")

print("TEST completed")

打开和关闭“监听”是父进程中的一个注意事项。


推荐阅读