使用Python

时间:2018-10-25 09:20:24

标签: python python-2.7 batch-file cmd

我正在尝试从批处理文件中获取退出代码。更具体地说,我在获取错误级别时遇到问题。

我尝试使用Popen,check_output,call,check_call:

   out = os.system(BatchFilePath)
   out, err = subprocess.Popen(BatchFilePath,stderr=subprocess.PIPE, shell=True).communicate()
   out,err = subprocess.Popen(BatchFilePath, stderr=subprocess.PIPE).communicate()
   out = subprocess.Popen(BatchFilePath,  shell=True).stderr
   out = os.system(BatchFilePath)
   out = subprocess.check_call(BatchFilePath)
   out = subprocess.call(BatchFilePath, shell=True)
   out = subprocess.check_output(buildPath, shell=True)

大多数时候返回空或0

我也尝试使用

SET ERRORLEVEL=1
exit /B !ERRORLEVEL!

但没有运气。我也尝试过

    set RC=
    setlocal
    somecommand.exe
    endlocal & set RC=%ERRORLEVEL%
    exit /B %RC%

另一种方法是

out, err = subprocess.Popen(BatchFilePath,stdout=subrocess.PIPE,stderr=subprocess.PIPE, shell=True).communicate()

,然后从out变量中搜索字符串“ ERROR”或“ FAILURE”。

另一方面,用户将看不到批处理文件中的所有回显,因此直到批处理文件完成并从我的python脚本中打印相应的消息之前,屏幕将是空的,没有任何消息。

因此,我不需要使用Popen中的stdout = subrocess.PIPE选项,因为它可以打印批处理中的所有回显。

我正在使用CMD,而不是Powershell。 我正在使用python 2.7

我在Google和此处进行了搜索,但找不到任何可以帮助我的东西。 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

要使用subprocess.Popen获取返回码,请使用poll()wait()方法。

下面是使用poll()的示例:

proc = subprocess.Popen('ls')
proc.communicate()
retcode = proc.poll()

此处的文档:https://docs.python.org/2/library/subprocess.html#subprocess.Popen.poll

根据您的评论,我使用批处理脚本检查了

SET ERRORLEVEL=1
exit /B !ERRORLEVEL!

如果您将!替换为%,则可以使用

SET ERRORLEVEL=1
exit /B %ERRORLEVEL%

答案 1 :(得分:0)

解决我的问题的方法确实很简单,但令人不知所措。

我替换了:

EXIT /B !ERRORLEVEL!

EXIT 1

我用了

os.system(BatchFilePath) 

覆盖所有其他内容。

谢谢@olricson,抽出宝贵的时间帮助我。我很感激。