【问题标题】:Python Script calling a shell script via os.system() exit code 256 instead of 1. Why?Python 脚本通过 os.system() 退出代码 256 而不是 1 调用 shell 脚本。为什么?
【发布时间】:2020-10-21 06:24:18
【问题描述】:

我正在编写一个 Python 脚本来处理不同 shell 脚本的退出代码。

当我通过命令提示符调用 shell 脚本并使用echo $? 询问退出代码时,我得到一个 1。 当我通过 python 脚本调用 shell 脚本时,我假设值是1,但结果却是 256。

发生了什么?

这是我用于测试相机的 shell 脚本:

#!/bin/bash 
#cam.sh

if [ -r /dev/video0 ]
then
    #taking a picture
    ffmpeg -f video4linux2 -s 640x480 -i /dev/dev0 -ss 0:0:2 -frames 1 ~/Desktop/testbild.jpg 2>/dev/null
    #showing a stream 
    timeout 10s vlc v4l2:///dev/video0 --no-audio --no-video-title-show
    exit 0
else
    exit 1
fi

还有我的 Python 调用:

#!/usr/bin/env python
#exitcodetest.py

import os

command = "sh ~/Desktop/cam.sh"
camera = os.system(command)
print(camera)

为什么?

【问题讨论】:

  • sh的返回码。是sh bash 吗?尝试command = "~/Desktop/cam.sh"(首先使用chmod +x
  • 脚本已经可以通过 chmod +x 运行。谢谢!
  • 文件扩展名是错误的格式,让调用者指定解释器也是如此。
  • @ctrl-alt-delor 我不太明白你想说什么?
  • AGeß 而不是 sh ~/Desktop/cam.sh 停止指定 shell 并直接运行脚本,~/Desktop/cam.sh

标签: shell python


【解决方案1】:

因为os.system 不返回退出代码而是返回等待状态。要将其转换为返回代码,您需要使用 os.waitstatus_to_exitcode(或 os.WEXITSTATUS 用于较旧的 Python 版本)。

In [2]: os.WEXITSTATUS(256)                                                                                                                                                                                       
Out[2]: 1

有关更多详细信息,请参阅 os.waitstatus_to_exitcodeos.system 的 python 文档。还有man systemman waipid 了解有关等待状态的更多详细信息。

此外,如果您需要一些更“用户友好”的方式从 Python 运行命令/程序,我建议使用 subprocess module

【讨论】:

  • 非常感谢!我现在使用camera = os.WEXITSTATUS(os.system(command)) 并得到假设的 1 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-26
  • 2011-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多