2017-02-14 80 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