【问题标题】:Multiple Commands with | in Python使用 | 的多个命令在 Python 中
【发布时间】:2012-12-25 01:59:36
【问题描述】:

我正在尝试通过Python 执行以下命令行。

Cat File |grepcidr -f file.name >>output.file

如果我使用 subprocess.call

subprocess.call(["cat", "File", "|", "grepcidr -f", "file.name", ">>output.file"])

它只是尝试Cat 一切。

任何帮助将不胜感激。

【问题讨论】:

标签: python-2.7


【解决方案1】:

琐碎但不可移植的方式:

subprocess.call(["/bin/sh","-c","cat File | grepcidr -f file.name >>output.file"])

它需要/bin/sh,如果您仍然依赖cat,这应该不是问题。我认为可以自己构建一系列协作的子流程:您必须像 /bin/sh 对管道和重定向所做的那样,但在 python 中。

【讨论】:

  • 谢谢 Anton :),现在只需要遍历所有文件名 ^_^
  • 使用 /bin/sh,每个 shell 构造都可用。也许shell的for循环会更容易写。
  • 对不起,我对 Python 很陌生,Shell 的 for 循环是什么意思?我基本上是在尝试 grepcird 一个带有关联文件的文件,并将每个文件的结果输出到一个新文件中。
  • 它与python无关,与/bin/sh有关(这就是为什么如果您是python新手,但对/bin/sh不太新,我推荐它)。 subprocess.call(["/bin/sh","-c","for file in *.myext; do cat $file | ...... >> output.file; done"])
  • 好的,这应该可以吗? subprocess.call(["/bin/sh","-c","for file in *.txt do cat $file |grepcidr -f $file >>$file+1.txt"])
猜你喜欢
  • 2013-12-01
  • 2021-04-26
  • 2020-04-01
  • 2017-06-16
  • 2013-06-21
  • 2013-11-11
  • 1970-01-01
  • 2016-07-08
  • 2021-11-01
相关资源
最近更新 更多