Python 为什么subprocess.Popen使用shell命令会有奇怪的格式?
我是Python新手。我的问题是: a) ShellHelper.py:Python 为什么subprocess.Popen使用shell命令会有奇怪的格式?,python,formatting,popen,Python,Formatting,Popen,我是Python新手。我的问题是: a) ShellHelper.py: import subprocess def execute_shell(shell): process = subprocess.Popen(shell, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output = process.communicate()[0] exit_code = process.returnc
import subprocess
def execute_shell(shell):
process = subprocess.Popen(shell, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = process.communicate()[0]
exit_code = process.returncode
if exit_code == 0:
return output
else:
raise Exception(shell, exit_code, output)
b) Launcher.py
from ShellHelper import *
command = input("Enter shell command: ")
out = execute_shell(command)
print(out.split())
c) 我的终端:
pc19:AutomationTestSuperviser F1sherKK$ python3 Launcher.py
Enter shell command: ls
[b'Launcher.py', b'ShellHelper.py', b'__pycache__']
b'
的奇怪格式李>
解码输出,将字节字符串转换为“常规”文本。列表由
split
创建,您可以join
使用空格字符来创建正常的ls
输出:
out = execute_shell(command).decode("utf-8")
print(" ".join(out.split()))
为了提供更清楚的答案,请考虑以下内容: 1) 进程的输出不是ASCII格式的,因此在文件开头看到的b表示字符串是二进制格式的 2) 您选择将列表返回到打印功能,如下所示:
'file1 file2 file3'.split() => ['file1', 'file2', 'file3']
这将在单独的行中打印每一行:
for foo in 'file1 file2 file3'.split():
print foo # this will also remove the b and print the ascii alone
2) 通过执行
out.split()
您正在运行Python3,其中所有字符串实际上都是unicode字符串(每个字符有2个字节)。字符串前面的“b”前缀表示该字符串是一个字节字符串(每个字符为1个字节)。这是因为系统返回一个bytestring,并且它不会像python那样以unicode“本机”运行。我没有注意到。我想在那里脱衣。