Skip to main content
 首页 » 编程设计

python之带引号的子进程命令不起作用

2024年10月01日7wayfarer

我的子进程命令无法使用引号。

tail = subprocess.Popen('tail -f -n 1 /mnt/syslog/**/*.log | egrep -v \'^$|mnt\'',\ 
            shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 

当我执行 python file.py 时,我得到一个空行:

# python main.py  
^CTraceback (most recent call last): 
  File "main.py", line 18, in <module> 
    main() 
  File "main.py", line 12, in main 
    line = tail.stdout.readline() 
KeyboardInterrupt 

如您所见,它在 bash 中运行良好:

# tail -f -n 1 /mnt/syslog/**/*.log | egrep -v '^$|mnt' 
Sep  9 22:44:07 x.x.x.x : %LINK-3-UPDOWN: Interface GigabitEthernet1/0/19, changed state to down 
Sep  9 18:32:56 x.x.x.x : %LINK-5-CHANGED: Interface GigabitEthernet1/0/24, changed state to administratively down 

怎么了?

请您参考如下方法:

我认为问题根本不是引号。

该命令正在执行 tail -f,根据定义,它永远不会终止(它会一直跟踪文件)。当您在 shell 中调用它时,您会立即看到一些输出(可能取决于 grep 是否匹配)。但它可能不会返回到提示符,因为 tail 仍在运行。

如果你真的想关注文件,那么你不应该使用 communicate() 因为它需要一个终止过程。您必须继续从 stdout(和 stderr,以确保安全!)读取数据,直到进程结束。

但我怀疑您需要做的就是删除尾部的 -f :

tail = subprocess.Popen('tail -n 1 /mnt/syslog/**/*.log | egrep -v \'^$|mnt\'',\ 
        shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) 

如果您删除 -f,那么 communicate() 就是正确的调用方式。

或者,您可以只使用 check_output 助手:

subprocess.check_output('tail...', shell=True)