我正在尝试从批处理文件中获取退出代码。更具体地说,我在获取错误级别时遇到问题。
我尝试使用 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
我在谷歌和这里搜索,但找不到任何对我有帮助的东西。 任何帮助将不胜感激。
最佳答案
要使用 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%
关于python - 使用 Python 从批处理文件中获取退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52985752/