我是一个学习python和在命令行中工作的新手。
我读到该子过程是鼓励的方式,而不是os.system。我正在创建一个调用shell的脚本,但是我还不能使用子进程来完成。不过,使用os.system轻而易举:
os.system("cut -f1-4 " + temp1.name + "| uniq --count | sort -rn > " + temp2.name)我成功地将subprocess用于其他命令,但不是那些将多个工具与"|“组合在一起的命令。读取子进程python文档令人困惑,对我也没有帮助。我也尝试过搜索其他问题,但找不到与我的问题相似的东西。这是我尝试过的(但失败了):
subprocess.call = (["cut", "-f1-4", temp1.name, "|", "uniq", "--count", "|", "sort". "-rn"], stdout = open(temp2.name, 'w'))我也尝试过用sp.Popen替换sp.call,但失败了。有没有人能帮我举一些清晰的例子和解释?谢谢!
发布于 2012-10-15 16:26:48
如果你想使用管道,你应该添加shell=True
subprocess.check_output("cut -f1-4 " + temp1.name + "| uniq --count | sort -rn > " + temp2.name, shell=True)请注意,如果temp1.name或temp2.name来自不受信任的来源(例如,来自web应用程序中用户提供的数据),则使用shell=True是一个安全风险。
发布于 2012-10-15 16:44:13
值得一看的是伟大的库python sh,它是一个成熟的Python子进程接口,允许您像调用函数一样调用任何程序,更重要的是,它是令人愉快的Python。
对于你在这种情况下的特殊需求,它提供了一些“高级管道”特性,比如:
# the inner command executes first, then sends its data to the outer command
from sh import *
sort(uniq(cut("-f1-4", _in="temp1.name"), "--count"), "-rn", _out="temp2.name")https://stackoverflow.com/questions/12891724
复制相似问题