How to determine pid of process started via os.system

谁都会走 提交于 2019-12-05 05:27:09

os.system return exit code. It does not provide pid of the child process.

Use subprocess module.

import subprocess
import time
argument = '...'
proc = subprocess.Popen(['python', 'bar.py', argument], shell=True)
time.sleep(3) # <-- There's no time.wait, but time.sleep.
pid = proc.pid # <--- access `pid` attribute to get the pid of the child process.

To terminate the process, you can use terminate method or kill. (No need to use external kill program)

proc.terminate()

Sharing my solution in case it can help others:

I took the info from this page to run a fortran exe in the background. I tried to use os.forkpty to get the pid of it, but it didnt give the pid of my process. I cant use subprocess, because I didnt find out how it would let me run my process on the background.

With help of a colleague I found this:

exec_cmd = 'nohup ./FPEXE & echo $! > /tmp/pid'

os.system(exec_cmd)

In case of wanting to append pids to the same file, use double arrow.

You could use os.forkpty() instead, which, as result code, gives you the pid and fd for the pseudo terminal. More documentation here: http://docs.python.org/2/library/os.html#os.forkpty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!