Python 如何从标准输出编辑字符串

Python 如何从标准输出编辑字符串,python,subprocess,netsh,Python,Subprocess,Netsh,我有以下代码: 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) 结果

我有以下代码:

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'

如何获得这样的输出“托管网络停止成功”?

从子进程读取将为您提供一个bytestring。您可以通过TestRing对其进行解码(您必须找到合适的编码),或者使用
universal\u newlines
选项,让Python为您自动解码:

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


如果universal\u newlines为
True
,则这些文件对象将使用
locale.getpreferredencode(False)
返回的编码以universal newlines模式作为文本流打开。对于
stdin
,输入中的行尾字符
'\n'
将转换为默认的行分隔符
os.linesep
。对于
stdout
stderr
,输出中的所有行尾都将转换为
'\n'
。有关更多信息,请参阅当构造函数的换行符参数为
None
io.TextIOWrapper
类的文档


对于通过shell运行的进程,
locale.getpreferredencoding(False)
应该是正确的编解码器,因为它从其他进程(如
netsh
应该参考的位置)获取关于使用何种编码的信息

使用
universal\u newlines=True
output
将设置为托管网络停止的字符串
\n\n';注意末尾的换行符。您可能需要使用
str.strip()`删除多余的空白:

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

这是一个bytestring。更改代码以使其成为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())

不要假设UTF-8总是正确的。明确指定编解码器;对于通过shell运行的外部进程,
locale.getpreferredencoding(False)
的返回值将是一个很好的猜测。谢谢你,Bishakh。
locale.getpreferredencoding(False)
相当于Windows上的ANSI代码页,如cp1252,但stdout编码可能是OEM代码页,如
cmd.exe中的cp437(在Windows上由
shell=True
运行)。我不知道
netsh
在这里使用什么字符编码。@J.F.Sebastian:hrmz,所以netsh是一个Windows命令,我错过了它。我找不到关于它产生什么输出以及消息的本地化程度的任何信息。:-/