使子进程 find git 在 Windows 上可执行

发布于 2024-10-16 15:51:35 字数 273 浏览 1 评论 0原文

import subprocess

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

我的系统路径中有 git,但是当我像这样运行子进程时,我得到:
WindowsError: [Error 2] 系统找不到指定的文件

如何让子进程在系统路径中查找 git?

Windows XP 上的 Python 2.6。

import subprocess

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

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

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

Python 2.6 on Windows XP.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

独孤求败 2024-10-23 15:51:35

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

import subprocess

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

shell==Truegit 起作用的原因是 Windows shell 自动- 将 git 解析为 git.cmd

最后,自己解析 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()

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()

The reason git works when shell==True is that the Windows shell auto-resolves git to git.cmd.

Eventually, resolve git.cmd yourself:

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()
不喜欢何必死缠烂打 2024-10-23 15:51:35

您的意思是

proc = subprocess.Popen(["git", "status"], stdout=subprocess.PIPE)

subprocess.Popen 的第一个参数采用类似 shlex.split 的参数列表。

或者:

proc = subprocess.Popen("git status", stdout=subprocess.PIPE, shell=True)

不建议这样做,因为您要启动 shell,然后在 shell 中启动进程。

另外,您应该使用 stdout=subprocess.PIPE 来检索结果。

You mean

proc = subprocess.Popen(["git", "status"], stdout=subprocess.PIPE)

The first argument of subprocess.Popen takes a shlex.split-like list of arguments.

or:

proc = subprocess.Popen("git status", stdout=subprocess.PIPE, shell=True)

This is not recommended, as you are launching a shell then launching a process in the shell.

Also, you should use stdout=subprocess.PIPE to retrieve the result.

总攻大人 2024-10-23 15:51:35

请注意,到 2020 年,Git 2.28(2020 年第 3 季度)将不再支持 Python 2.6 或更早版本。

请参阅 提交 45a87a8(2020 年 6 月 7 日),作者:刘丹顿 (Denton-L)
(由 Junio C Hamano -- gitster -- 合并于 提交 6361eb7,2020 年 6 月 18 日)

CodingGuidelines:指定Python 2.7是最旧的版本

签字人:刘丹顿

0b4396f068中(“git-p4:使 python2.7 成为最旧的受支持版本”,2019-12-13,Git v2.27.0-rc0 -- 合并列于批次#1),git-p4是更新为仅支持 2.7 及更高版本。由于 Python 2.6 已经是相当古老的历史,因此请更新 CodingGuidelines 以显示 2.7 是受支持的最旧版本。

Note that in 2020, with With Git 2.28 (Q3 2020), Python 2.6 or older is no longer supported.

See commit 45a87a8 (07 Jun 2020) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 6361eb7, 18 Jun 2020)

CodingGuidelines: specify Python 2.7 is the oldest version

Signed-off-by: Denton Liu

In 0b4396f068 ("git-p4: make python2.7 the oldest supported version", 2019-12-13, Git v2.27.0-rc0 -- merge listed in batch #1), git-p4 was updated to only support 2.7 and newer. Since Python 2.6 is pretty much ancient history, update CodingGuidelines to show that 2.7 is the oldest version supported.

何以畏孤独 2024-10-23 15:51:35

我相信您需要将 env 传递给 Popen,例如:

import subprocess, os
proc = subprocess.Popen('git status', env=os.environ, stdout=subprocess.PIPE)

应该可以解决问题。

I believe you need to pass env in to Popen, something like:

import subprocess, os
proc = subprocess.Popen('git status', env=os.environ, stdout=subprocess.PIPE)

Should do the trick.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文