简体   繁体   中英

Opens a process with Popen cant close it ( need to run Ros command in cmd)

I need to save some image files from my simulation at different times. So my idea was to open a subprocess save some image files and close it .

import subprocess

cmd = "rosrun pcl_ros pointcloud_to_pcd input:=camera/depth/points"
proc = subprocess.Popen(cmd, shell=True)

When it comes to closing I tried different things:

import os
import signal
import subprocess

cmd = "rosrun pcl_ros pointcloud_to_pcd input:=camera/depth/points"
pro = subprocess.Popen(cmd, stdout=subprocess.PIPE, 
                       shell=True, preexec_fn=os.setsid) 

os.killpg(os.getpgid(pro.pid), signal.SIGTERM)

command did not execute , so it doesn't work for me. I also tried a solution with psutil and it didn't work neither...

you probably don't need shell=True here, which is the cause of your problems. I suspect that when you kill the process group in your second snippet, the shell process is killed before the process you want to run has a chance to start...

Try to pass the parameters as a list of strings (so you don't need shell=True ), wait a bit, and use kill on the Popen object. You don't need process group, or psutil to kill the process & its children, just plain old kill() on the process object does the trick.

cmd = ["rosrun","pcl_ros","pointcloud_to_pcd","input:=camera/depth/points"]
proc = subprocess.Popen(cmd)
time.sleep(1)  # maybe needed to wait the process to do something useful
proc.kill()

EDIT: seems that this "shot in the dark" worked. Another plea for "do not use shell=True unless forced at gunpoint".

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