Skip to main content
 首页 » 编程设计

python之如何从 STDOUT 编辑字符串

2024年10月17日24cloudgamer

我有这个代码:

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。您可以解码这个字节串(您必须找到合适的编码),或者使用 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=True,output 将设置为字符串'The hosted network stopped。\n\n';注意末尾的换行符。您可能想使用 str.strip()` 删除那里多余的空格:

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