使用Python打开cmd,得到结果并进行相应操作

Use Python to open cmd, get the result and proceed accordingly

我需要一个代码,其中 Python 可以调用 cmd 进程,运行 一个命令。

我必须确定该命令是否成功,然后在 python 代码中进行相应处理。

我在 Whosebug 上找到的代码只处理打开 cmd 和 运行ning 命令。

我不想使用 runas,因为它需要管理员权限,我稍后将其合并到我的程序中,不应在此处使用。(仅在不调用 UAC 时才建议使用并且不需要管理员权限。

我发现 运行 cmd 没有管理员权限的唯一代码是:

command = "cmd.exe" 
proc = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = subprocess.PIPE)

我不知道 proc 变量是否可以用来检测 return 值或任何其他东西,请相应地指导我并尽可能建议更好的代码。

是的,Popen的结果可以用来检测return的值并输出,但是用subprocess.run更容易。来自 Python docs:

subprocess.run(["ls", "-l"])  # doesn't capture output

result = subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE) # returns a CompletedProcess

你可以审问result(同样来自docs):

result.returncode # process return code
result.stdout # std out from the process