Python 为什么subprocess.Popen使用shell命令会有奇怪的格式?

Python 为什么subprocess.Popen使用shell命令会有奇怪的格式?,python,formatting,popen,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.returnc

我是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__']
  • 为什么在每个文件之前都会出现类似
    b'
    的奇怪格式
  • 它必须是列表吗
  • 我是否需要进行更多格式化,使其成为一个清晰的字符串

  • 解码输出,将字节字符串转换为“常规”文本。列表由
    split
    创建,您可以
    join
    使用空格字符来创建正常的
    ls
    输出:

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

    为了提供更清楚的答案,请考虑以下内容:

    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
    

    2) 通过执行
    out.split()
    您正在运行Python3,其中所有字符串实际上都是unicode字符串(每个字符有2个字节)。字符串前面的“b”前缀表示该字符串是一个字节字符串(每个字符为1个字节)。这是因为系统返回一个bytestring,并且它不会像python那样以unicode“本机”运行。我没有注意到。我想在那里脱衣。