簡體   English   中英

捕獲在終端中在變量中運行的命令的 output

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

我正在嘗試捕獲從運行到變量中的 python 腳本中獲得的所有數據。 我在腳本中從用戶那里獲取了一些輸入,我想從頭到尾捕獲所有內容。

幾乎與此類似: 運行 shell 命令並捕獲 output

但這再次使用腳本中的子進程來獲取 output。

我想要的是這樣的:

當我在終端中運行 ls -l 時,我希望我的腳本捕獲 ls -l 的輸出

如果我寫:

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

在我的腳本中,這將執行腳本兩次。

當我在終端中運行 ls -l 時,預期的 output 將捕獲所有數據以在 p2 中捕獲。

如果您想避免顯式使用 subprocess.Popen subprocess.Popen()的所有麻煩,只需 go 用於os.popen("command").read() - 它在引擎蓋下運行前者,在我的情況下是p2 = os.popen("ls -l").read()看起來恰到好處。

您可以使用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)

這是一個foo.py

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

從終端運行它時會發生以下情況:

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

當您從日志記錄腳本運行它時,會發生以下情況:

$ ./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