简体   繁体   English

将我的 shell 脚本的 output 存储在变量中

[英]Storing the output of my shell script in a variable

Using the following code:使用以下代码:

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)

Basically I am trying to emulate terminal as a whole.基本上我试图模拟终端作为一个整体。 But I am sort of failing.但我有点失败。 Stuff like ps -A Doesn't give an output at all.ps -A这样的东西根本不会给出 output 。 Any help..?任何帮助..?

Use subprocess.check_output .使用subprocess.check_output The encoding argument convert the output bytes to str . 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)

Note that CalledProcessError is raise if the exit code is not zero.请注意,如果退出代码不为零,则会引发CalledProcessError

Alternatively, subprocess.run with capture_output=True may be used.或者,可以使用带有capture_output=Truesubprocess.run The output is stored in the returned CompletedProcess.stdout and no exception whatever the exit code is. 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)

I actually did what you did and hosted it over on github ( https://github.com/Pythers/PyCMD/blob/master/ main .py )我实际上做了你所做的并将它托管在 github ( https://github.com/Pythers/PyCMD/blob/master/ main .py )

I believe your problem is that you need to set the stdout to the normal instead of subprocess.PIPE我相信您的问题是您需要将标准输出设置为正常而不是 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