pythonsubprocess.call()找不到WindowsBash.ex

2024-04-25 17:56:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个程序,它从运行在新的windows子系统linux上的另一个程序获得输出。我已经编写了一个从windows系统运行的python程序,但是将使用python subprocess模块来执行linux程序。如果这令人困惑,请参阅下面的示例。在

然而,当我这样做时,我发现当通过python子进程调用时,windows找不到bash程序。在

windows中的命令行或powershell示例:

C:\>bash -c "echo hello world!"
hello world!

C:\>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess as s
>>> s.call('bash -c "echo hello world"'.split())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\Python27-32\lib\subprocess.py", line 524, in call
    return Popen(*popenargs, **kwargs).wait()
  File "c:\Python27-32\lib\subprocess.py", line 711, in __init__
    errread, errwrite)
  File "c:\Python27-32\lib\subprocess.py", line 948, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

>>> s.call('bash -c "echo hello world"'.split(),shell=True)
    'bash' is not recognized as an internal or external command,
    operable program or batch file.
    1

我想也许它没有加载我的路径设置,所以我输入了bash程序的完整地址。在

^{pr2}$

编辑:我意识到我的命令可能会出现问题,因为o在空间上分裂,“echo hello world”是一个参数,但是用bash -c ls尝试同样的操作也会产生相同的错误


Tags: orinpyecho程序bashhelloworld
1条回答
网友
1楼 · 发布于 2024-04-25 17:56:56

对于在WOW64子系统中运行的32位程序,“System32”目录gets redirected到“SysWOW64”。华尔街日报bash.exe加载程序是作为64位可执行文件分发的,因此从32位Python中,您需要使用虚拟的“SysNative”目录。例如:

import os
import platform
import subprocess

is32bit = (platform.architecture()[0] == '32bit')
system32 = os.path.join(os.environ['SystemRoot'], 
                        'SysNative' if is32bit else 'System32')
bash = os.path.join(system32, 'bash.exe')

subprocess.check_call('"%s" -c "echo \'hello world\'"' % bash)

请注意,当前Windows管道没有桥接到WSL管道,因此如果您尝试使用stdout=PIPE或{},WSL bash加载程序将失败。您可以通过ReadConsoleOutputCharacter直接读取控制台输出(例如,请参见this answer)。或者,更简单地说,您可以将输出重定向到临时文件,将临时文件的路径转换为WSL路径。例如:

^{pr2}$

编辑:从WindowsBuild14951开始,您应该能够使用stdout=PIPE。请参阅WSL博客文章Windows and Ubuntu Interoperability。在

相关问题 更多 >