如何从 STDOUT 编辑字符串

How to edit string from STDOUT

我有这个代码:

netshcmd = subprocess.Popen('netsh wlan stop hostednetwork', shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
output, errors = netshcmd.communicate()
if errors:
    print("Warrning: ", errors)
else:
    print("Success", output)

输出是这样的:

Success b'The hosted network stopped. \r\n\r\n'

如何获得这样的输出"Success The hosted network stopped."?

从子进程中读取给你一个 bytestring。你可以解码这个字节串(你必须找到合适的编码),或者使用 universal_newlines 选项并让 Python 自动为你解码:

netshcmd = subprocess.Popen(
    'netsh wlan stop hostednetwork', 
    shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE,
    universal_newlines=True)

来自Frequently Used Arguments documentation section

If universal_newlines is True, these file objects will be opened as text streams in universal newlines mode using the encoding returned by locale.getpreferredencoding(False). For stdin, line ending characters '\n' in the input will be converted to the default line separator os.linesep. For stdout and stderr, all line endings in the output will be converted to '\n'. For more information see the documentation of the io.TextIOWrapper class when the newline argument to its constructor is None.

对于通过 shell 的进程 运行,locale.getpreferredencoding(False) 应该 完全 使用正确的编解码器,因为它获取信息关于从 netsh 等其他进程应该咨询的完全相同的位置使用什么编码, locale environment variables.

对于 universal_newlines=Trueoutput 将设置为字符串 'The hosted network stopped. \n\n'; note the newlines at the end. You may want to usestr.strip()` 以删除那里多余的空格:

print("Success", output.strip())

那是字节串。更改您的代码以使其成为 str:

netshcmd = subprocess.Popen('netsh wlan stop hostednetwork', shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
output, errors = netshcmd.communicate()
if errors:
    print("Warrning: ", errors.decode())
else:
    print("Success", output.decode())