如何从STDOUT编辑字符串

2024-04-19 16:03:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码:

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'

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


Tags: true密码outputshellsuccesssubprocessstopprint
2条回答

那是一个副测试环。更改代码使其成为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())

从子进程中读取数据会给您一个bytestring。您可以对这个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())

相关问题 更多 >