2017-02-14 77 views
0

我是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__'] 
  1. 爲什麼在每個文件之前,我會得到這種奇怪的格式,如b'
  2. 是否需要列表?
  3. 我需要更多的格式,所以它是一個明確的字符串?
+1

2)你做了它通過執行out.split()列表# – TemporalWolf

+0

您正在運行Python 3,其中所有字符串實際上都是unicode字符串(每個字符都是2個字節)。字符串前面的'b'前綴表示該字符串是一個字節字符串(每個字符都是1個字節)。這是因爲系統返回一個字節串,並且它不像python那樣在unicode中「本地」運行。 – Zizouz212

+0

哦'分裂'是無意的。我沒有注意到。我想在那裏試試。 – F1sher

回答

0

解碼輸出以將字節字符串轉換爲「常規」文本。由split創建的列表,你可以join列表用空格字符來創建正常ls輸出:

out = execute_shell(command).decode("utf-8") 
print(" ".join(out.split())) 
0

爲了提供更明確的答案,考慮以下因素:

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