如何在Python中以管理员身份运行cmd命令

11 投票
1 回答
26581 浏览
提问于 2025-04-18 18:54

我想用Python 3来运行一个Windows命令,比如用os.system("echo hi")。但是,如果要运行一个需要管理员权限的命令,该怎么做呢?谢谢。

1 个回答

11

你可以使用一个叫做 ShellExecuteEx 的 Win32 API 封装,这个封装包含在 Pywin32 扩展里。如果你正在使用像 ActivePython 这样的工具,你可能已经有这些扩展了。

要使用 ShellExecuteEx:

import win32com.shell.shell as shell
commands = 'echo hi'
shell.ShellExecuteEx(lpVerb='runas', lpFile='cmd.exe', lpParameters='/c '+commands)

撰写回答