简体   繁体   English

捕获在终端中在变量中运行的命令的 output

[英]Capture output of a command ran in terminal in a variable

I am trying to capture all the data that I get from a python script that I run into a variable.我正在尝试捕获从运行到变量中的 python 脚本中获得的所有数据。 I took a few inputs from the user within the script and I want to capture everything from start till the end.我在脚本中从用户那里获取了一些输入,我想从头到尾捕获所有内容。

It is almost similar to this: Running shell command and capturing the output几乎与此类似: 运行 shell 命令并捕获 output

But again this uses the subprocess within the script to get an output.但这再次使用脚本中的子进程来获取 output。

What I want is something like this:我想要的是这样的:

when i run ls -l in the terminal, I want my script to capture the ouput of ls -l当我在终端中运行 ls -l 时,我希望我的脚本捕获 ls -l 的输出

If i write:如果我写:

p2 = subprocess.Popen('ls','-l',stdout= subprocess.PIPE).communicate()[0])

within my script, that will execute the script twice.在我的脚本中,这将执行脚本两次。

The expected output is to capture all the data when i run ls -l in the terminal to be captured in p2.当我在终端中运行 ls -l 时,预期的 output 将捕获所有数据以在 p2 中捕获。

If you want to avoid all the hassle of using subprocess.Popen() explicitly, just go for os.popen("command").read() - it runs the former under the hood, and in my case the result of p2 = os.popen("ls -l").read() looks just right.如果您想避免显式使用 subprocess.Popen subprocess.Popen()的所有麻烦,只需 go 用于os.popen("command").read() - 它在引擎盖下运行前者,在我的情况下是p2 = os.popen("ls -l").read()看起来恰到好处。

You can use pexpect to easily open a PTY and log everything it shows:您可以使用pexpect轻松打开 PTY 并记录它显示的所有内容:

#!/usr/bin/env python3
import pexpect
import io

print("-- Running the program")
p = pexpect.spawn("./foo.py")
p.logfile_read = io.BytesIO()
p.interact();

print("-- Program exited. Here is the log:")
log = p.logfile_read.getvalue().decode("utf-8")
print(log)

Here's a foo.py :这是一个foo.py

#!/usr/bin/env python3
name=input("Enter name: ")
print("Hello " + name)

Here's what happens when you run it from a terminal:从终端运行它时会发生以下情况:

$ ./foo.py
Enter name: World
Hello World

And here's what happens when you run it from the logging script:当您从日志记录脚本运行它时,会发生以下情况:

$ ./log.py
-- Running the program
Enter name: World
Hello World
-- Program exited. Here is the log:
Enter name: World
Hello World

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM