Linux,将输出写入文件并使用Python终止它

时间:2021-11-16 14:07:21

There are various topics available on this very topic, "How to write output to the text file". But my issue is different because the output to the command in question is continous.

在这个主题“如何将输出写入文本文件”中提供了各种主题。但我的问题是不同的,因为有问题的命令的输出是连续的。

What I want to do is, write the Output of the command cgps -s to the file aaa.txt

我想要做的是,将命令cgps -s的输出写入文件aaa.txt

here is the code,

这是代码,

import signal
import os
import subprocess
p = subprocess.Popen(["cgps", "-s", ">> aaa.txt"], stdout=subprocess.PIPE,shell=True, preexec_fn=os.setsid)
os.killpg(p.pid, signal.SIGTERM)

The code doesn't work at all and no file is created with the name aaa.txt

代码根本不起作用,并且没有使用名称aaa.txt创建文件

When I execute this command through terminal,

当我通过终端执行此命令时,

cgps -s > aaa.txt

Then I have to press CTRL+C to terminate the output from being written on the output file because the output is continuous.

然后我必须按CTRL + C来终止输出写入输出文件,因为输出是连续的。

Is there any way to just capture one output and write it to the file and terminate it using Python or using Command line ?

有没有办法只捕获一个输出并将其写入文件并使用Python或使用命令行终止它?

1 个解决方案

#1


1  

So you are trying to create a pipe. Try this:

所以你正在尝试创建一个管道。尝试这个:

import subprocess

p = subprocess.Popen(["cgps", "-s"], stdout=subprocess.PIPE)

with open("aaa.txt", "w") as f:
    while True:
        line = p.stdout.readline()
        if not line:
            break
        if some_condition(): # <-- check whether you have enough output
            p.terminate()
            break
        f.writeline(line)

p.wait()

#1


1  

So you are trying to create a pipe. Try this:

所以你正在尝试创建一个管道。尝试这个:

import subprocess

p = subprocess.Popen(["cgps", "-s"], stdout=subprocess.PIPE)

with open("aaa.txt", "w") as f:
    while True:
        line = p.stdout.readline()
        if not line:
            break
        if some_condition(): # <-- check whether you have enough output
            p.terminate()
            break
        f.writeline(line)

p.wait()