为什么有奇怪的格式子流程.Popen用shell命令?

2024-10-01 09:24:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手。我的问题是:

(一)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)

(二)启动器.py在

^{pr2}$

c)我的终端:

pc19:AutomationTestSuperviser F1sherKK$ python3 Launcher.py 
Enter shell command: ls
[b'Launcher.py', b'ShellHelper.py', b'__pycache__']
  1. 为什么我要在每个文件之前使用这种奇怪的格式,比如b'?在
  2. 一定要单列吗?在
  3. 我需要更多的格式以使它是一个清晰的字符串吗?在

Tags: pyimport名称output格式exitcode公司
2条回答

解码输出以将字节字符串转换为“常规”文本。列表是由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']

这将在单独的行中打印每一行:

^{pr2}$

相关问题 更多 >