python - 子处理管道写入文件故障

标签 python shell unix subprocess pipe

在 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])

我所说的“什么都没有”是指文件中的空白输出。有没有人在这里看到任何不寻常的地方?

最佳答案

我总是使用 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

关于python - 子处理管道写入文件故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15401836/

相关文章:

python - 如果给出一个文件作为参数或标准输入,是否有更多的 pythonic 方式打开文件?

python - 无法将python变量传递给hive -e

python - 在 matplotlib 中向时间轴添加填充

python - 对另一个二维数组的二维数组的每一行执行数学运算

java - 有什么方法可以在 Java 中调用 shell 脚本并通过 Java 类为 shell 脚本变量设置值

linux - 如何在 vi 编辑器中获取关键字的颜色。 ***不在 ViM 中***

python - 如何覆盖 pandas 中索引的对象表示

linux - 当 read = 0 时停止读数

linux - Unix 脚本在读取行 "No such file or directory"错误时循环 cat 文件

linux - 可以有多个init.pp吗?