在Windows 2008 SP2中从Python运行bcdedit

0 投票
4 回答
1552 浏览
提问于 2025-04-15 17:43

我对Windows不太熟悉,这可能就是我遇到问题的原因……

我想在Windows 2008R2上通过Python 2.6运行bcdedit命令。

我用来运行命令的Python代码大致是这样的:

def run_program(cmd_str):
    """Run the specified command, returning its output as an array of lines"""
    dprint("run_program(%s): entering" % cmd_str)
    cmd_args = cmd_str.split()
    subproc = subprocess.Popen(cmd_args, stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE, shell=True)
    (outf, errf) = (subproc.stdout, subproc.stderr)
    olines = outf.readlines()
    elines = errf.readlines()
    if Options.debug:
        if elines:
            dprint('Error output:')
            for line in elines:
                dprint(line.rstrip())
        if olines:
            dprint('Normal output:')
            for line in olines:
                dprint(line.rstrip())
    errf.close()
    outf.close()
    res = subproc.wait()
    dprint('wait result=', res)
    return (res, olines)

我这样调用这个函数:

(res, o) = run_program('bcdedit /set {current} MSI forcedisable')

这个命令在命令提示符窗口中输入时可以正常工作,放在批处理文件里并从命令窗口运行(当然是以管理员身份)也没问题。

但是当我从Python中运行它(也是以管理员身份)时,Python却说找不到这个命令,返回的信息是:

bcdedit is not recognized as an internal or external command,
operable program or batch file

而且,如果我尝试从Python运行我的批处理文件(这个文件在命令行中可以正常工作),它也会失败。我还尝试过用bcdedit的完整路径,结果也是一样。

从Python调用bcdedit时,为什么会找不到这个命令呢?

需要注意的是,我可以从Python调用其他的EXE文件,所以我对我的Python代码还是有一定信心的……但谁知道呢。

任何帮助都会非常感激。

4 个回答

0

可能在某些情况下,当你运行Python时,bcdedit.exe的路径没有包含在系统的路径中(比如说,使用了不同的用户账户)。你可以通过打印出来来检查这一点:

os.environ.get("PATH")

路径是用分号分隔的,所以用os.environ.get("PATH").split(';')来查看可能会更有帮助。

我想不出有什么理由它不在那里的,但为了保险起见,你应该检查一下C:\Windows\System32这个地方,其中的C是你Windows系统的盘符。

0

检查一下你的PATH变量,看看里面有没有C:\windows\system32这个路径。你可以在命令提示符下输入set来查看。

1

Windows 2008 R2是只能用64位的,对吧?而Python是一个32位的程序。当一个32位的应用程序要运行位于C:\Windows\System32的东西时,Windows其实会去C:\Windows\SysWOW64这个地方找。你可以使用C:\Windows\SysNative来解决这个问题。

撰写回答