簡體   English   中英

將我的 shell 腳本的 output 存儲在變量中

[英]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=Truesubprocess.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM