让子进程在Windows上找到git可执行文件 [英] Make subprocess find git executable on Windows

查看:564
本文介绍了让子进程在Windows上找到git可执行文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import subprocess

proc = subprocess.Popen('git status')
print 'result: ', proc.communicate()

在我的系统路径中有git,但是当我像这样运行子进程时,得到:

WindowsError:[错误2]系统找不到指定的文件

I have git in my system path, but when I run subprocess like this I get:
WindowsError: [Error 2] The system cannot find the file specified

如何获取子进程git在系统路径中?

How can I get subprocess to find git in the system path?

Windows XP上的Python 2.6。

Python 2.6 on Windows XP.

推荐答案

您在这里看到的问题是Windows API函数 CreateProcess 由子进程使用,不会自动解析除 .exe 之外的其他可执行扩展。在Windows上,'git'命令实际上被安装为 git.cmd 。因此,您应该修改您的示例以显式调用 git.cmd

The problem you see here is that the Windows API function CreateProcess, used by subprocess under the hood, doesn't auto-resolve other executable extensions than .exe. On Windows, the 'git' command is really installed as git.cmd. Therefore, you should modify your example to explicitly invoke git.cmd:

import subprocess

proc = subprocess.Popen('git.cmd status')
print 'result: ', proc.communicate()

shell == True git $ c>是Windows外壳自动解析 git git.cmd

import subprocess
import os.path

def resolve_path(executable):
    if os.path.sep in executable:
        raise ValueError("Invalid filename: %s" % executable)

    path = os.environ.get("PATH", "").split(os.pathsep)
    # PATHEXT tells us which extensions an executable may have
    path_exts = os.environ.get("PATHEXT", ".exe;.bat;.cmd").split(";")
    has_ext = os.path.splitext(executable)[1] in path_exts
    if not has_ext:
        exts = path_exts
    else:
        # Don't try to append any extensions
        exts = [""]

    for d in path:
        try:
            for ext in exts:
                exepath = os.path.join(d, executable + ext)
                if os.access(exepath, os.X_OK):
                    return exepath
        except OSError:
            pass

    return None

git = resolve_path("git")
proc = subprocess.Popen('{0} status'.format(git))
print 'result: ', proc.communicate()

这篇关于让子进程在Windows上找到git可执行文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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