python - 如何从 STDOUT 编辑字符串

标签 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)

输出是这样的:

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 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) 应该完全使用正确的编解码器,因为它获取有关要使用的编码的信息locale environment variablesnetsh 等其他进程应该引用的位置完全相同。 .

使用universal_newlines=Trueoutput将设置为字符串'托管网络已停止。\n\n';请注意末尾的换行符。您可能需要使用str.strip()`来删除那里多余的空格:

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

关于python - 如何从 STDOUT 编辑字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40068695/

相关文章:

python - 如何将自定义图像放置到QMessageBox上

python - 如何让 Bokeh 图像像 matplotlib 一样在左上角绘制原点?

Python Hadoop 流错误 "ERROR streaming.StreamJob: Job not Successful!"和堆栈跟踪 : ExitCodeException exitCode=134

.net - 从程序内部管理 HTTPS 服务器证书?

python 轮子 : cp27mu not supported

python - 当命令从命令提示符正确执行时,在 subprocess.call() 中使用 find 会出错

python - 使用 Python 子进程模块运行具有 10 个以上参数的批处理文件

http - 为什么 netsh http add sslcert 从 Powershell ps1 文件中抛出错误?

windows - 无法保存旧的 netsh http urlacl 保留

python - 如何将斐波那契数列保存到列表中?