【发布时间】:2017-05-22 07:28:25
【问题描述】:
我正在使用来自Centos 6 平台的Python 2.6.6。
我需要在后台从 Python 运行一个包含重定向运算符的 bash 命令,并且需要从子进程对象中读取后台进程的 pid。
我试过下面的代码sn-ps,但是还是不行。
我的代码:
import subprocess
# Below code throws child_exception
myProcess = subprocess.Popen('tail -f -n 0 /home/user123/mainFile.txt >> /home/user123/tailFile.txt &', subprocess.PIPE)
#If I use the below command, terminating the process kills
#only the shell process and leaves the tail process as orphan
myProcess = subprocess.Popen('tail -f -n 0 /home/user123/mainFile.txt >> /home/user123/tailFile.txt', shell=True, subprocess.PIPE)
cmd = ['tail', '-f', '-n', '0', '/home/user123/mainFile.txt', '>>', '/home/user123/tailFile.txt', '&']
#Below line throws bash error saying: "cannot open file '>>'"
myProcess = subprocess.Popen(cmd, stdout=subprocess.PIPE)
myProcessPid = myProcess.communicate()[0]
最后我需要获取在后台运行的尾部进程的 pid。
【问题讨论】:
-
>>,&是 shell 元字符;除非您将shell=True与subprocess.Popen一起使用,否则它不会使用shell,并且这些元字符将被逐字解释...... -
我尝试使用
shell=True并尝试将其作为列表和字符串提供。我能够获得正确的进程 ID,但在 bash 中只启动没有任何参数的尾部进程。
标签: python linux bash subprocess