我是Python新手。这里是我的问题:为什么subprocess.Popen与shell命令有奇怪的格式?
一)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.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())
三)我的终端:
pc19:AutomationTestSuperviser F1sherKK$ python3 Launcher.py
Enter shell command: ls
[b'Launcher.py', b'ShellHelper.py', b'__pycache__']
- 为什么在每个文件之前,我会得到这种奇怪的格式,如
b'
? - 是否需要列表?
- 我需要更多的格式,所以它是一个明确的字符串?
2)你做了它通过执行out.split()列表# – TemporalWolf
您正在运行Python 3,其中所有字符串实际上都是unicode字符串(每个字符都是2个字节)。字符串前面的'b'前缀表示该字符串是一个字节字符串(每个字符都是1个字节)。这是因为系统返回一个字节串,并且它不像python那样在unicode中“本地”运行。 – Zizouz212
哦'分裂'是无意的。我没有注意到。我想在那里试试。 – F1sher