为什么使用shell命令从subprocess.Popen中出现奇怪的格式?

时间:2017-02-14 23:50:04

标签: 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.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__']
  1. 为什么我会在每个文件之前得到像b'这样奇怪的格式?
  2. 是否必须列出?
  3. 我是否需要更多格式化,因此它是一个清晰的字符串?

2 个答案:

答案 0 :(得分:0)

将输出解码为从字节字符串转换为"常规"文本。该列表由split创建,您可以join带有空格字符的列表来创建正常的ls输出:

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

答案 1 :(得分: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