首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何启动、停止和获取另一个python程序的输出

如何启动、停止和获取另一个python程序的输出
EN

Stack Overflow用户
提问于 2019-06-04 01:19:09
回答 2查看 100关注 0票数 -2

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

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

我看过关于如何获取另一个python程序的控制台输出,以及如何启动和停止它的指南,但我还没有找到关于这两个方面的指南。

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

谢谢。

编辑:不是复制品,它不是那么简单...

EDIT2:

这是我的尝试

main.py

代码语言:javascript
复制
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

代码语言:javascript
复制
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‘

EDIT3:

代码语言:javascript
复制
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程序中的其他代码,但这不起作用。

代码语言:javascript
复制
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()
代码语言:javascript
复制
import time


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


if __name__ == "__main__":
    main()

EDIT4:是我尝试同时运行这两个程序的尝试

代码语言:javascript
复制
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()
代码语言:javascript
复制
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,但我不能准确地弄清楚如何让它工作。

EN

回答 2

Stack Overflow用户

发布于 2019-06-04 01:57:08

当我问了一个类似的问题时,下面是我是如何做到的。输出一打印出来,我就需要它,而不是等待缓冲区填充。

子进程

代码语言:javascript
复制
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")

父进程

代码语言:javascript
复制
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")

在父进程中,打开和关闭“侦听”是一个需要注意的问题。

票数 1
EN

Stack Overflow用户

发布于 2019-06-04 01:40:03

对于最初的评论,我很抱歉。

我知道一种方法,但我不确定它是否在所有操作系统上都有效。它涉及到subprocess模块:

代码语言:javascript
复制
import subprocess
import os
#another python file with possible inputs
command = "python3 test2.py"
#get current file dir as thats where test2.py is located
fileDir = os.path.dirname(os.path.realpath(__file__))
#gets outputs printed on the terminal
process = subprocess.check_output(command.split(), cwd=fileDir)
print(process)

这种方法还可以确保在继续主代码之前完成第二个脚本。

编辑:输出为字节形式,使用类似process.decode('utf-8')的格式进行解码

更多here

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56431877

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档