3

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?

1
  • 2
    iirc subprocess.call returns the exit code.. so you could just check if script==0 ? Commented Nov 14, 2013 at 7:20

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

0

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()

4 Comments

Because I am trying to teach myself other methods, so even if this is less simplistic, its a learning exercise for myself.
"The try-expect construct is only used for handling exceptions that modules can throw. It should never be used as an alternative to if-else." learnpythonthehardway.org/book/ex48.html
Thank you :), by the way, is there a way to pipe unix errors that moutnscript my encounter to a text file?
... which probably doesn't work as intended or ist at least bad style: if you use shell=True, you should use a string, not a list of strings. Better do with open("file.txt", "w") as f: script = subprocess.check_call(['mountscript.sh'], stderr=f)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.