gpt4 book ai didi

string - 如何在 Python 2 和 Python 3 中处理 subprocess.Popen 输出

转载 作者:行者123 更新时间:2023-12-01 14:37:49 28 4
gpt4 key购买 nike

我有一个简单的函数来检查程序是否正在运行并根据需要返回一个 bool 值。它通过检查命令 ps -A 的输出来做到这一点。使用模块subprocess .我试图让这个函数在 Python 2 和 Python 3 中都能工作,但遇到以下错误:

TypeError: a bytes-like object is required, not 'str'

应该如何更改函数以便它可以在 Python 2 和 Python 3 中工作?
import subprocess

def running(program):
results = subprocess.Popen(
["ps", "-A"],
stdout = subprocess.PIPE
).communicate()[0].split("\n")
matches_current = [
line for line in results if program in line and "defunct" not in line
]
if matches_current:
return True
else:
return False

编辑:遵循@Josh 的一些指导,我已将换行符字符串分隔符更改为字节码,但是我仍然遇到类似的问题:
>>> import subprocess
>>> def running(program):
... results = subprocess.Popen(
... ["ps", "-A"],
... stdout = subprocess.PIPE
... ).communicate()[0].split(b"\n")
... matches_current = [
... line for line in results if program in line and "defunct" not in line
... ]
... if matches_current:
... return True
... else:
... return False
...
>>> running("top")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in running
File "<stdin>", line 7, in <listcomp>
TypeError: a bytes-like object is required, not 'str'

最佳答案

使用像 b"\n" 这样的字节串而不是简单的 "\n" , 并使用 program.encode()而不是 program (假设你被传递一个字符串):

results = subprocess.Popen(
["ps", "-A"],
stdout = subprocess.PIPE
).communicate()[0].split(b"\n")
matches_current = [
line for line in results if program.encode() in line and b"defunct" not in line
]

这是因为在 Python 3 中, subprocess.Popen.communicate默认情况下返回字节而不是字符串。在 Python 2.6+ 中, b"\n" == "\n" ,所以你不应该有任何问题。

关于string - 如何在 Python 2 和 Python 3 中处理 subprocess.Popen 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48169667/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com