有没有办法在没有换行符和其他冗余字符的情况下打印子进程的输出?

Is there a way to print the output of subprocess without the newline and other redundant characters?

假设我这里有这个简短的脚本:

import subprocess

some = subprocess.run("ls", shell=True, capture_output=True)
print(some.stdout)

当我用最后一条语句打印出输出时,我得到了这个:

b'main.py\nprogram.cpp\nreadme.txt\nsomefile.c\n'

有谁知道如何在不使用 字母 b、单引号、反斜杠和换行符的情况下打印相同的输出? 并用 " 分隔每个 file/directory隐形”换行符?

问题是您收到 bytes 而不是字符串。您可以通过打印 type(some.stdout) 来检查。因此,您需要使用 method of the same namebytes 解码为字符串。像这样:

print(some.stdout.decode('utf-8'))