2011-11-03 22 views
15

我工作的一個漂亮的小功能:打開與POPEN的過程和獲取PID

def startProcess(name, path): 
    """ 
    Starts a process in the background and writes a PID file 

    returns integer: pid 
    """ 

    # Check if the process is already running 
    status, pid = processStatus(name) 

    if status == RUNNING: 
     raise AlreadyStartedError(pid) 

    # Start process 
    process = subprocess.Popen(path + ' > /dev/null 2> /dev/null &', shell=True) 

    # Write PID file 
    pidfilename = os.path.join(PIDPATH, name + '.pid') 
    pidfile = open(pidfilename, 'w') 
    pidfile.write(str(process.pid)) 
    pidfile.close() 

    return process.pid 

的問題是,process.pid不正確的PID。看起來總是比正確的PID低1。例如,它說,這個過程開始於31729,但ps說,它運行在31730.每次我試了一下功能是關閉的1。我猜它返回的PID是當前進程的PID,而不是時間開始一個,新的過程獲得'下一個'pid,這是更高的1。如果是這樣,我不能僅僅依靠返回process.pid + 1,因爲我不能保證它總是正確的。

爲什麼不process.pid返回PID的新進程,我如何能實現我以後的行爲嗎?

+1

嘗試刪除'shell = True'和你的'''東西。 – Blender

+0

我有同樣的問題,我發現困難的方式,它並不總是PID + 1,這是第一次,但現在它給了我+2 – andrei

回答

19

從文檔在http://docs.python.org/library/subprocess.html

Popen.pid The process ID of the child process.

Note that if you set the shell argument to True, this is the process ID of the spawned shell.

如果shell是假的,它應該表現爲你所期望的,我想。

+0

我需要'shell = True'爲Python的相對路徑工作。我想我會用絕對路徑替換它,並將'shell'設置爲false。感謝您的信息! – Hubro

+1

首先通過os.path.abspath傳遞路徑應該爲你解決這個問題。 http://docs.python.org/library/os.path.html –

+0

Nah,運行'os.path.abspath('python')'只返回我的工作目錄和'python',例如'/ root/python' – Hubro