Python linux-收听打开的终端标准输出
假设我有一个独立于python脚本的开放终端。是否可以以某种方式收听此终端标准输出?如果需要捕获所需的确切过程,可以使用Python linux-收听打开的终端标准输出,python,linux,ubuntu,Python,Linux,Ubuntu,假设我有一个独立于python脚本的开放终端。是否可以以某种方式收听此终端标准输出?如果需要捕获所需的确切过程,可以使用strace 假设你有两个终端。 从第一个终端运行ping命令 ping google.com PING google.com (xxx.xxx.xxx.xxx) 56(84) bytes of data. 64 bytes from muc11s14-in-f14.1e100.net (xxx.xxx.xxx.xxx): icmp_seq=1 ttl=116 time=11.
strace
假设你有两个终端。
从第一个终端运行ping
命令
ping google.com
PING google.com (xxx.xxx.xxx.xxx) 56(84) bytes of data.
64 bytes from muc11s14-in-f14.1e100.net (xxx.xxx.xxx.xxx): icmp_seq=1 ttl=116 time=11.5 ms
64 bytes from muc11s14-in-f14.1e100.net (xxx.xxx.xxx.xxx): icmp_seq=2 ttl=116 time=10.9 ms
64 bytes from muc11s14-in-f14.1e100.net (xxx.xxx.xxx.xxx): icmp_seq=3 ttl=116 time=11.3 ms
64 bytes from muc11s14-in-f14.1e100.net (xxx.xxx.xxx.xxx): icmp_seq=4 ttl=116 time=11.4 ms
...
现在切换到第二终端并运行:
strace-e trace=write-s1000-fp$(pgrep ping)
此时,我们得到了另一个终端的输出。让我们转到python部分
from subprocess import Popen, PIPE, STDOUT, check_output
import shlex
process_id = check_output(shlex.split("pgrep ping"), text=True).strip()
p = Popen(
shlex.split("strace -e trace=write -s1000 -fp {0}".format(process_id)),
stdin=PIPE, stdout=PIPE, stderr=STDOUT, text=True
)
for line in p.stdout:
print(line.strip())
迭代p.stdout
,您将获得另一个终端的进程输出
strace: Process 765549 attached
write(1, "64 bytes from ber01s08-in-f238.1e100.net (xxx.xxx.xxx.xxx): icmp_seq=732 ttl=116 time=11.4 ms\n", 93) = 93
write(1, "64 bytes from ber01s08-in-f238.1e100.net (xxx.xxx.xxx.xxx): icmp_seq=733 ttl=116 time=11.3 ms\n", 93) = 93
write(1, "64 bytes from ber01s08-in-f238.1e100.net (xxx.xxx.xxx.xxx): icmp_seq=734 ttl=116 time=11.4 ms\n", 93) = 93
write(1, "64 bytes from ber01s08-in-f238.1e100.net (xxx.xxx.xxx.xxx): icmp_seq=735 ttl=116 time=11.5 ms\n", 93) = 93
write(1, "64 bytes from ber01s08-in-f238.1e100.net (xxx.xxx.xxx.xxx): icmp_seq=736 ttl=116 time=11.3 ms\n", 93) = 93
如果通过
子流程
模块从Python脚本中启动此终端,则可以通过相关管道进行读写。查看更多信息。是的,我知道这一点,但是我想要听的终端独立于python脚本。那么,我认为你不能。如果这个过程是从别处开始的,你就不能钩住它的流,这就像劫持一样understand@omEchan如果您有权访问该终端,则可以让Python脚本持续读取该文件。
strace: Process 765549 attached
write(1, "64 bytes from ber01s08-in-f238.1e100.net (xxx.xxx.xxx.xxx): icmp_seq=732 ttl=116 time=11.4 ms\n", 93) = 93
write(1, "64 bytes from ber01s08-in-f238.1e100.net (xxx.xxx.xxx.xxx): icmp_seq=733 ttl=116 time=11.3 ms\n", 93) = 93
write(1, "64 bytes from ber01s08-in-f238.1e100.net (xxx.xxx.xxx.xxx): icmp_seq=734 ttl=116 time=11.4 ms\n", 93) = 93
write(1, "64 bytes from ber01s08-in-f238.1e100.net (xxx.xxx.xxx.xxx): icmp_seq=735 ttl=116 time=11.5 ms\n", 93) = 93
write(1, "64 bytes from ber01s08-in-f238.1e100.net (xxx.xxx.xxx.xxx): icmp_seq=736 ttl=116 time=11.3 ms\n", 93) = 93