Joseph
Joseph

Reputation: 357

Checking if subprocess call executed successfully

So I am still teaching myself Python and I wanted to created a small script for my server that will tell me if my HDD is mounted and if not to mount it for me when I sign in. (I have it in ~/.bashrc).

The problem I am facing is this:

try:
    with open('/media/Hitachi/mountfile.txt', 'r') as f:
        print(f.readline())
except:
        print('HDD is not mounted')
        if not os.path.exists('/media/Hitachi/media'):
                print('Attempting to mount HDD')
                script = subprocess.call('mountscript.sh', shell=True)

How can I find out if mountscript.sh succeeded or not?

Upvotes: 3

Views: 5218

Answers (2)

Back2Basics
Back2Basics

Reputation: 7806

why not a simple if/else statement and use check_call

if os.path.exists('/media/Hitachi/mountfile.txt'):
    print("it's mounted")
else:
    print('HDD is not mounted')
    if not os.path.exists('/media/Hitachi/media'):
        print('Attempting to mount HDD')
        script = subprocess.check_call(['mountscript.sh','2>file.txt'], shell=True)

Regardless of that, the moral of the story is don't forget the brackets around the command arguments to subprocess.call() or check_call()

Upvotes: 0

Taylan Aydinli
Taylan Aydinli

Reputation: 4363

subprocess.call method returns the returncode of the process so you can check that to see whether the call succeeded.

>>> subprocess.call(["ls", "-l"])
0
>>> subprocess.call("exit 1", shell=True)
1

Upvotes: 4

Related Questions