subprocess.call返回int无法判断进程,如何获取字符串输出?
解答你的subprocess相关问题
咱们一步步来拆解,其实你的两个疑问本质上是同一个核心误解导致的:
核心问题:subprocess.call()的返回值不是命令输出!
subprocess.call()只返回命令的退出状态码(整数类型)——0表示命令执行成功,非0表示失败。这就是为什么你会遇到两个错误:
- 试图判断
'networking' in tmp时,报错TypeError: argument of type 'int' is not iterable:你没法在整数里查找字符串 - 尝试给
tmp加.decode()时失败:整数类型根本没有这个方法
正确的解决方案:获取命令的输出内容
要拿到ps -A的执行结果,你需要使用专门捕获输出的subprocess方法,推荐用Python 3.5+官方推荐的subprocess.run(),或者subprocess.check_output()。
方法1:使用subprocess.run()(推荐)
这个方法更灵活,能同时获取输出、退出码等信息:
import subprocess try: # 传入命令参数列表(避免shell=True,更安全可靠),捕获输出并转为字符串 result = subprocess.run( ['ps', '-A'], capture_output=True, text=True, stderr=subprocess.DEVNULL ) # 从result中提取命令输出的字符串内容 ps_output = result.stdout if 'networking' in ps_output: print("networking service is up and running!") else: print("networking service is not up :(") except Exception as e: print(f"执行命令时出错:{e}")
text=True(或universal_newlines=True,旧版本用法)会自动把字节流转为字符串,无需手动.decode()- 用参数列表
['ps', '-A']代替字符串'ps -A'+shell=True,能避免shell注入风险,兼容性更好
方法2:使用subprocess.check_output()
如果只需要命令的标准输出,这个方法更简洁:
import subprocess try: # 直接获取命令输出的字符串内容 ps_output = subprocess.check_output( ['ps', '-A'], stderr=subprocess.DEVNULL, text=True ) if 'networking' in ps_output: print("networking service is up and running!") else: print("networking service is not up :(") except subprocess.CalledProcessError: print("ps命令执行失败") except Exception as e: print(f"其他错误:{e}")
关于问题1的补充:int转字符串的通用方法
如果在其他场景下你确实需要把整数转为字符串,直接用str(your_integer)就可以,比如:
num = 123 str_num = str(num) print(type(str_num)) # 输出 <class 'str'>
但在你的这个场景里,根本不需要把subprocess.call()的返回值转字符串——因为它本来就不是你需要的命令输出内容。
额外小建议:检查服务状态更可靠的方式
如果你的系统是用systemd管理服务的(大多数现代Linux发行版),用systemctl命令检查服务状态会比解析ps输出更准确:
import subprocess try: # 检查networking服务是否活跃 result = subprocess.run( ['systemctl', 'is-active', 'networking'], capture_output=True, text=True ) # 活跃状态会输出"active" if result.stdout.strip() == 'active': print("networking service is up and running!") else: print("networking service is not up :(") except Exception as e: print(f"检查服务状态出错:{e}")
内容的提问来源于stack exchange,提问作者Kosem
相关产品推荐
相关产品推荐

