将命令重定向到 Python 中另一个命令的输入
我想在 python 中复制此内容:
gvimdiff <(hg cat file.txt) file.txt
(hg cat file.txt 输出 file.txt 最近提交的版本)
我知道如何将文件通过管道传输到 gvimdiff,但它不会接受另一个文件:
$ hg cat file.txt | gvimdiff file.txt -
Too many edit arguments: "-"
进入 python 部分...
# hgdiff.py
import subprocess
import sys
file = sys.argv[1]
subprocess.call(["gvimdiff", "<(hg cat %s)" % file, file])
当子进程被调用时,它只是将 <(hg cat file)
作为文件名传递到 gvimdiff
上。
那么,有没有办法像 bash 那样重定向命令呢? 为了简单起见,只需 cat 一个文件并将其重定向到 diff:
diff <(cat file.txt) file.txt
I would like to replicate this in python:
gvimdiff <(hg cat file.txt) file.txt
(hg cat file.txt outputs the most recently committed version of file.txt)
I know how to pipe the file to gvimdiff, but it won't accept another file:
$ hg cat file.txt | gvimdiff file.txt -
Too many edit arguments: "-"
Getting to the python part...
# hgdiff.py
import subprocess
import sys
file = sys.argv[1]
subprocess.call(["gvimdiff", "<(hg cat %s)" % file, file])
When subprocess is called it merely passes <(hg cat file)
onto gvimdiff
as a filename.
So, is there any way to redirect a command as bash does?
For simplicity's sake just cat a file and redirect it to diff:
diff <(cat file.txt) file.txt
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可以办到。 然而,从 Python 2.5 开始,这种机制是 Linux 特定的并且不可移植:
也就是说,在 diff 的特定情况下,您可以简单地从 stdin 中获取其中一个文件,并且无需使用类似于 bash 的功能问题:
It can be done. As of Python 2.5, however, this mechanism is Linux-specific and not portable:
That said, in the specific case of diff, you can simply take one of the files from stdin, and remove the need to use the bash-alike functionality in question:
还有命令模块:
如果您想在命令运行时实际获取命令中的数据,还有 popen 函数集。
There is also the commands module:
There is also the popen set of functions, if you want to actually grok the data from a command as it is running.
这实际上是 docs 中的一个示例:
这对您来说意味着:
这会删除使用特定于 Linux 的 /proc/self/fd 位,使其可以在其他 unice 上工作,例如 Solaris 和 BSD(包括 MacOS),甚至可以在 Windows 上工作。
This is actually an example in the docs:
which means for you:
This removes the use of the linux-specific /proc/self/fd bits, making it probably work on other unices like Solaris and the BSDs (including MacOS) and maybe even work on Windows.
我突然意识到您可能正在寻找 popen 函数之一。
来自: http://docs.python.org/lib/module-popen2.html< /a>
popen3(cmd[, bufsize[, 模式]])
作为子进程执行 cmd。 返回文件对象(child_stdout、child_stdin、child_stderr)。
合十礼,
标记
It just dawned on me that you are probably looking for one of the popen functions.
from: http://docs.python.org/lib/module-popen2.html
popen3(cmd[, bufsize[, mode]])
Executes cmd as a sub-process. Returns the file objects (child_stdout, child_stdin, child_stderr).
namaste,
Mark