不使用管道从子进程读取输出

时间:2016-09-05 07:05:43

标签: windows bash pipe subprocess windows-subsystem-for-linux

我试图运行bash.exe(在Ubuntu for Windows上使用Bash)作为Sublime Text的构建命令。但是,bash.exe有一个错误,不支持将其stdout输出到任何管道。

问题是:如何运行cmd行(即" bash.exe -c ls")并捕获输出而不将bash.exe输出到Windows上的管道中?

我愿意在Windows上使用任何语言或环境来制作此工具。

修改

我跑了 bashTest = subprocess.Popen(["bash.exe", "-c", "ls"]), stdout=subproccess.PIPE)

产生了:

bashTest.communicate()[0] b'E\x00r\x00r\x00o\x00r\x00:\x00\x000\x00x\x008\x000\x000\x007\x000\x000\x005\x007\x00\r\x00\r\x00\n\x00'

3 个答案:

答案 0 :(得分:1)

目前无法做到这一点。其中github issue about it作为已知限制被关闭。如果您想提高对它的认识,我会看到2个相关的用户语音提示:Allow Windows programs to spawn BashAllow native Win32 applications to launch Linux tools/commands

但是,有很多方法可以解决它。一种方法是编写一个在bash.exe控制台中永远循环的脚本。当脚本获得信号时,它会运行Linux命令,输出通过管道传输到文件,然后表示它已完成。这里有一些伪代码:

Linux的:

while true
  while not exists /mnt/c/dobuild
    sleep 1
  end
  gcc foo.c > /mnt/c/build.log
  rm /mnt/c/dobuild
end

视窗:

touch C:\dobuild
while exists C:\dobuild
  sleep 1
end
cat C:\build.log

这确实要求在脚本运行时始终打开bash.exe控制台,这是不理想的。

已经提到的另一个潜在的解决方法是使用ReadConsoleOutput

答案 1 :(得分:0)

您需要使用选项shell=True in Popen()才能使管道正常工作。

就像这个例子一样,不需要拆分这个命令。

>>> import subprocess as sp    
>>> cmd = 'echo "test" | cat'
>>> process = sp.Popen(cmd,stdout=sp.PIPE,shell=True)
>>> output = process.communicate()[0]
>>> print output
test

答案 2 :(得分:0)

如果您不能等待修复,唯一可行的选择是使用ReadConsoleOutput和/或相关功能。