在shell中执行此命令会得到实际的结果:
wget -O c1 --no-cache "http://some.website" | sed "1,259d" c1 | sed "4,2002d"
在Python中这样做不会给我带来任何好处:
subprocess.call(shlex.split("wget -O c1 --no-cache \"http://some.website/tofile\""))
c1 = open("c1",'w')
first = subprocess.Popen(shlex.split("sed \"1,259d\" c1"), stdout=subprocess.PIPE)
subprocess.Popen(shlex.split("sed \"4,2002d\""), stdin=first.stdout, stdout=c1)
c1.close()
这样做也不会得到任何结果:
c1.write(subprocess.Popen(shlex.split("sed \"4,2002d\""), stdin=first.stdout, stdout=subprocess.PIPE).communicate()[0])
所谓“一无所获”,我指的是文件中的空白输出。有没有人看到什么不寻常的东西?
发布于 2013-03-14 16:47:44
语句c1 = open("c1",'w')
打开文件c1
进行写入,并截断任何现有数据,因此在调用sed之前,写入该文件的所有wget都会被擦除。
无论如何,我认为shlex.split
通常是笨拙的。我更喜欢手动构建args列表:
from subprocess import Popen, PIPE
p0 = Popen(['wget', '-O', '-', 'http://www.google.com'], stdout=PIPE)
p1 = Popen(['sed', '2,8d'], stdin=p0.stdout, stdout=PIPE)
with open('c1', 'w') as c1:
p2 = Popen(['sed', '2,7d'], stdin=p1.stdout, stdout=c1)
p2.wait()
但是,Python程序员没有明显的理由必须调用sed。Python有字符串方法和正则表达式。此外,您可以使用urllib2.urlopen
而不是wget。
发布于 2013-03-14 14:46:15
我总是使用plumbum来运行外部命令。它提供了一个非常直观的界面,当然,也为我提供了转义功能。
看起来像这样:
from plumbum.cmd import wget, sed
cmd1 = wget['-O', 'c1']['--no-cache']["http://some.website"]
cmd2 = sed["1,259d"]['c1'] | sed["4,2002d"]
print cmd1
cmd1() # run it
print cmd2
cmd2() # run it
发布于 2013-03-14 14:18:52
为什么不在管道中做所有的事情并将输出发送到一个文件中呢?
wget -O - "http://www.google.com" | sed "1,259d" | sed "4,2002d" > c1
或者,如果您不想将其发送到文件,而希望将其放在stdout上:
wget -O - "http://www.google.com" | sed "1,259d" | sed "4,2002d"
如果你想用Python做这件事:
pipe = subprocess.Popen(shlex.split("wget -O - \"http://www.google.com\" | sed \"1,259d\" | sed \"4,2002d\""), stdout=subprocess.PIPE)
result = pipe.communicate()[0]
https://stackoverflow.com/questions/15401836
复制相似问题