简体   繁体   中英

subprocess popen Python

i am executing a shell script which is starting a process with background option &. The shell script is called from python script which hangs.

Shell script:

test -f filename -d &

python file

cmd =["shellscript","restart"]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,  
                        stderr=subprocess.PIPE, stdin=subprocess.PIPE, **kwargs)
pid = proc.pid
out, err = proc.communicate()
returncode = proc.poll()

Python file hangs and it won't return out of the python process. Also python process is an automated one.

The call to proc.communicate() will block until the pipes used for stderr and stdout are closed. If your shell script spawns a child process which inherits those pipes, then it will exit only after that process also has closed its writing ends of the pipes or exited.

To solve this you can either

  • redirect the output of the started subprocess to /dev/null or a logfile in your shell script, eg:
    subprocess_to_start >/dev/null 2>&1 &
  • use subprocess.DEVNULL or an open file object for stderr and stdout in your python script and drop the communicate() call if you don't need the output of "shellscript" in python

您的cmd列表中缺少逗号:

cmd =["shellscript", "restart"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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