Skip to main content
 首页 » 编程设计

python subprocess.call 和管道

2024年10月01日6oomusou

<分区>

我有一个脚本,我在其中尝试使用 subprocess.call 来执行一系列 shell 命令,但在执行时似乎省略了一些命令。

具体来说:

#!/usr/bin/python 
import tempfile 
import subprocess 
import os 
import re 
 
 
grepfd, grepfpath = tempfile.mkstemp(suffix=".xx") 
sedfd,  sedfpath  = tempfile.mkstemp(suffix=".xx") 
 
# grepoutfile = open( grepfpath, 'w') 
sedoutfile  = open( sedfpath,  'w' ) 
 
subprocess.call(['cp','/Users/bobby/Downloads/sample.txt', grepfpath]) 
 
sedcmd = [ 'sort',  
           grepfpath, 
           '|',  
           'uniq', 
           '|', 
           'sed', 
           '-e', 
           '"s/bigstring of word/ smaller /"', 
           '|', 
           'column', 
           '-t', 
           '-s', 
           '"=>"' ] 
 
print "sedcmd = ", sedcmd 
subprocess.call( ['ls', grepfpath ] ) 
subprocess.call( ['sort', '|', 'uniq' ], stdin = grepfd ) 
subprocess.call( sedcmd,  stdout = sedoutfile ) 

它生成这个作为输出:

python d3.py

sedcmd = ['sort',/var/folders/3h/_0xwt5bx0hx8tgx06cmq9h_4f183ql/T/tmp5Gp0ff.xx', '|', 'uniq', '|', 'sed', '-e', '"s/bigstring of word/smaller/"', '|', 'column', '-t', '-s', '"=>"'] /var/folders/3h/_0xwt5bx0hx8tgx06cmq9h_4f183ql/T/tmp5Gp0ff.xx 排序:打开失败:|:没有那个文件或目录
排序:无效选项 -- e 尝试 `sort --help' 获取更多信息。

第一个 'sort: open failed: |:No such file... 来自第一个子进程调用 ['sort','|','uniq'], stdin = grepfd ) 'sort: invalid option -- e .. 来自第二个子进程调用 (sedcmd)。

我已经看到很多在这种情况下使用管道的例子——那么我做错了什么?
谢谢!