我是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