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