python - 使用 Python 从批处理文件中获取退出代码

标签 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

我在谷歌和这里搜索,但找不到任何对我有帮助的东西。 任何帮助将不胜感激。

最佳答案

要使用 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/

相关文章:

python - 如何提高 OpenCV cv2.VideoCapture(0).read() 的性能

python - 如何在 OSX 上通过 Python Tkinter 安装和使用 TkDnD?

batch-file - 使用批处理删除文本文件的行

java - 为什么找不到 JAR 中的模块?

python - 如何从 Python 中的 NIC(网络接口(interface) Controller )获取 IP 地址?

python - 在 Shell 和 SQLAlchemy 中编辑 Python 类

python - 如何根据用户输入更新和保存Python脚本(仅变量,无逻辑)?

Python:从字典中删除大量键的最快策略

将文件解压缩到目录中的 Windows 批处理脚本

c - 如何从c程序获取输入到批处理文件作为返回值