执行Linux命令并获取PID

2024-05-17 05:43:47 发布

您现在位置:Python中文网/ 问答频道 /正文

通常我使用:

os.popen("du folder >> 1.txt ").read()

它工作得很好。
但是当我想要获取子进程id时,它返回空值。

os.popen("du folder >> 1.txt &").read() # Notice the & symbol

有人知道为什么和如何得到PID吗?


Tags: thetxtidread进程osfoldersymbol
2条回答

&将进程置于后台并输入作业号!=pid。获取进程的pid。

我建议使用subprocess-aPopen实例具有可以直接访问的属性pid

您需要使用subprocess模块。

# Can't use shell=True if you want the pid of `du`, not the
# shell, so we have to do the redirection to file ourselves
proc = subprocess.Popen("/usr/bin/du folder", stdout=file("1.txt", "ab"))
print "PID:", proc.pid
print "Return code:", proc.wait()

相关问题 更多 >