子进程 - 使用几个命令行工具 [英] Subprocess - using several command line tools

查看:173
本文介绍了子进程 - 使用几个命令行工具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个学习新手的python和工作在命令行,例如。管道。

I'm a learning newbie to python and to working in the command line, e.g. piping.

我已经读过那个子进程是鼓励方式,而不是os.system。我创建一个脚本调用shell,我不能够使用子进程。使用os.system是一个快照:

I've read that subprocess is encouraged way instead of os.system. I'm creating a script which invokes the shell and I have not been able to do it using subprocess. Using os.system was a snap though:

os.system("cut -f1-4 " + temp1.name + "| uniq --count | sort -rn > " + temp2.name)

子进程成功执行其他命令,但不能将多个工具与|组合。阅读子进程python文档是混乱,对我没有帮助。我也试过搜索其他问题,但找不到类似我的问题。这是我试过(失败):

I've used subprocess with success for other commands, but not those that combine more than one tools with "|". Reading the subprocess python documentation was confusing and not helpful to me. I've also tried searching other questions but could not find something similar to my problem. This is what I've tried (and failed):

subprocess.call = (["cut", "-f1-4", temp1.name, "|",  "uniq", "--count", "|", "sort". "-rn"], stdout = open(temp2.name, 'w'))

我也试过用sp.Popen替换sp.call,但失败。任何人都可以帮助一些清楚的例子和解释?
谢谢!

I've also tried substituting sp.call with sp.Popen, but failed. Can anyone please help with some clear examples and explanation? Thanks!

推荐答案

如果你想使用管道,你应该添加 shell = / code>

If you want to use pipes you should add shell=True

subprocess.check_output("cut -f1-4 " + temp1.name + "| uniq --count | sort -rn > " +    temp2.name, shell=True)

如果 temp1.name temp2.​​name 来自不受信任的来源(例如来自用户在网络应用程序)使用 shell = True 是一种安全风险。

Please note that if temp1.name or temp2.name come from an untrusted source (e.g. from data supplied by a user in a web application) using shell=True is be a security risk.

这篇关于子进程 - 使用几个命令行工具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆