我有以下代码:

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


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


对于通过外壳运行的进程,locale.getpreferredencoding(False)应该是正确使用的编解码器,因为它可以从与其他进程(例如netsh进行协商)完全相同的位置获取有关使用哪种编码的信息。 >。

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

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

08-04 17:31