简体   繁体   English

如何在 Python 中使用 subprocess.Popen() 而不是 os.popen()?

[英]How to use subprocess.Popen() instead of os.popen() in Python?

Since os.popen is deprecated, I wanted to use subprocess.Popen (and also because it is a lot more robust in every sense).由于 os.popen 已被弃用,我想使用 subprocess.Popen (也因为它在各个方面都更加健壮)。 I had this initially but can't figure out how to make the appropriate transition.我最初有这个,但不知道如何进行适当的过渡。

PID_FILE = 'process.pid'
if os.path.exists( PID_FILE ):
    pid = int(open( PID_FILE,'rb').read().rstrip('\n'))
    pinfo = os.popen('ps %i' % pid).read().split('\n')

Any help would be appreciated a lot.任何帮助将不胜感激。

Just use subprocess.Popen to create a new process, with its stdout redirected to a PIPE, in text mode and then read its stdout.只需使用subprocess.Popen创建一个新进程,将其标准输出重定向到 PIPE,在文本模式下,然后读取其标准输出。

Python version >= 3.6 Python 版本 >= 3.6

from subprocess import Popen, PIPE
with Popen(f'ps {pid}'.split(), stdout=PIPE, text=True) as proc:
    pinfo = proc.stdout.readlines()

As you have requested for python2.7, I have given the code.正如您对 python2.7 的要求,我已经给出了代码。 But remember that python2.7 has reached EOL and you should be using python3.x但请记住,python2.7 已达到 EOL,您应该使用 python3.x

Python version = 2.7 Python 版本 = 2.7

from subprocess import Popen, PIPE
proc = Popen(f'ps {pid}'.split(), stdout=PIPE)
pinfo = proc.stdout.readlines()

Refer subprocess documentation for more information有关更多信息,请参阅子流程文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM