[英]Storing the output of my shell script in a variable
使用以下代碼:
import subprocess
while(1==1):
command_terminal= input('Enter the command you would like to pass: ')
command_terminal=command_terminal.split()
result=subprocess.run(command_terminal, stdout=subprocess.PIPE)
result=result.stdout.decode('utf-8')
print(result)
基本上我試圖模擬終端作為一個整體。 但我有點失敗。 像ps -A
這樣的東西根本不會給出 output 。 任何幫助..?
使用subprocess.check_output
。 encoding
參數將 output bytes
轉換為str
。
import subprocess
while (1 == 1):
command_terminal = input('Enter the command you would like to pass: ')
command_terminal = command_terminal.split()
result = subprocess.check_output(command_terminal, encoding='utf-8')
print(result)
請注意,如果退出代碼不為零,則會引發CalledProcessError
。
或者,可以使用帶有capture_output=True
的subprocess.run
。 output 存儲在返回的CompletedProcess.stdout
中,無論退出代碼是什么都不例外。
import subprocess
while (1 == 1):
command_terminal = input('Enter the command you would like to pass: ')
command_terminal = command_terminal.split()
completed = subprocess.run(command_terminal, encoding='utf-8', capture_output=True)
result = completed.stdout
print(result)
我實際上做了你所做的並將它托管在 github ( https://github.com/Pythers/PyCMD/blob/master/ main .py )
我相信您的問題是您需要將標准輸出設置為正常而不是 subprocess.PIPE
import sys
import subprocess
while 1==1:
command_terminal= input('Enter the command you would like to pass: ')
command_terminal=command_terminal.split()
result=subprocess.run(command_terminal, stdout=sys.stdout)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.