我有这个代码:
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'
如何获得像这样的输出“成功托管网络已停止。”?
最佳答案
从子进程读取会得到一个字节串。您可以解码此字节字符串(您必须找到合适的编码),或者使用 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 bylocale.getpreferredencoding(False)
. Forstdin
, line ending characters'\n'
in the input will be converted to the default line separatoros.linesep
. Forstdout
andstderr
, all line endings in the output will be converted to'\n'
. For more information see the documentation of theio.TextIOWrapper
class when the newline argument to its constructor isNone
.
对于通过 shell 运行的进程,locale.getpreferredencoding(False)
应该完全使用正确的编解码器,因为它获取有关要使用的编码的信息locale environment variables 与 netsh
等其他进程应该引用的位置完全相同。 .
使用universal_newlines=True
,output
将设置为字符串'托管网络已停止。\n\n';请注意末尾的换行符。您可能需要使用
str.strip()`来删除那里多余的空格:
print("Success", output.strip())
关于python - 如何从 STDOUT 编辑字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40068695/