简体   繁体   中英

Python Script calling a shell script via os.system() exit code 256 instead of 1. Why?

I am writing a Python Script handling the exit codes of different shell scripts.

When i call the shell script via command prompt and ask for the exit code with echo $? , I get a 1. When I call the shell script via the python script, I assume the value will be 1 , but instead it turns out to be 256.

What happened?

This is my shell Script for testing a Camera:

#!/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

And my Python call:

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

import os

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

Why?

Because os.system doesn't return exitcode but waitstatus. To convert it to return code you need to use os.waitstatus_to_exitcode (or os.WEXITSTATUS for older Python versions).

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

See python documentation for os.waitstatus_to_exitcode and os.system for more details. And also man system and man waipid for more details on wait status.

Also if you need some more "user friendly" way of running commands/programs from Python, I recommend using the subprocess module .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM