Python子进程返回非零退出状态1。最小工作samp

2024-10-02 22:24:58 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么以管理员身份运行时此功能不起作用?在

import subprocess

command = "wbadmin get versions"
output = subprocess.check_output(["powershell", command], timeout=120)
print(output)

当我从powershell或cmd运行它时,它是有效的。在

当我使用Popen和communicate()时,我得到一个错误:

^{pr2}$

Tags: import功能cmdoutputget管理员checktimeout
2条回答

有问题的错误,评论倾向于指出这样一个事实:这里发布的代码很有可能不是您运行的代码(可能已经过时了?)。在

无论如何,运行您的精确的代码(保存在名为的文件中)代码.py)产量:

e:\Work\Dev\StackOverflow\q054334592>"e:\Work\Dev\VEnvs\py_064_03.06.08_test0\Scripts\python.exe" code.py
Traceback (most recent call last):
  File "code.py", line 4, in <module>
    output = subprocess.check_output(["powershell", command], timeout=120)
  File "c:\Install\x64\Python\Python\03.06.08\Lib\subprocess.py", line 356, in check_output
    **kwargs).stdout
  File "c:\Install\x64\Python\Python\03.06.08\Lib\subprocess.py", line 438, in run
    output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['powershell', 'wbadmin get versions']' returned non-zero exit status 1.

没有太多有用的信息。
但是check_output只是一个方便的包装器,在当前的情况下,它对我们不利。有关详细信息,请选中[Python 3]: subprocess - Subprocess management
所以我修改了你的代码。在

代码.py

import subprocess

ps_args = "wbadmin get versions"

cmd = ["powershell", *ps_args.split(" ")]  # It works with your way too (["powershell", ps_args]), I'm just being rigorous
print("Popen arguments: {:}".format(cmd))

proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate(timeout=120)

print("\nProcess terminated with exit code: {:}".format(proc.returncode))

print("\nSTDOUT:\n{:}\n".format(out.decode()))
print("STDERR:\n{:}\n".format(err.decode()))

这次的输出是:

e:\Work\Dev\StackOverflow\q054334592>"e:\Work\Dev\VEnvs\py_064_03.06.08_test0\Scripts\python.exe" code.py
Popen arguments: ['powershell', 'wbadmin', 'get', 'versions']

Process terminated with exit code: 1

STDOUT:
wbadmin 1.0 - Backup command-line tool
(C) Copyright Microsoft Corporation. All rights reserved.

ERROR - No backup was found.



STDERR:

现在,可以看到PSpowershell)命令运行尝试已成功运行,但命令本身,失败。因此,在子进程(和Python)方面(在使用check廕u output时,这一点并不十分清楚),问题就在PS一侧。在

万一我的备份失败了。但不管怎样,从这里看来,它更像是一个系统管理任务。在

在命令中使用完整路径。例如:

ps_args = "/etc/bin/wbadmin get versions" 

相关问题 更多 >