John Slathon
John Slathon

Reputation: 363

Python - Executing shell command does not work on Linux

I like to run a shell command from Python on my Linux Mint system. Specifically the command runs all Bleachbit cleaners and works perfectly fine when run maually.

Yet, trying to run the same command via the subprocess.call module always results in an exception raised.

I just can not see why it should not work. The command does not require sudo rights, so not requiring right not given.

I also have firefox/browsers closed when executing the python command.

Anybody, any suggestions how to fix this issue?

My code:

try:
    subprocess.call('bleachbit -c firefox.*') 
except:
    print "Error."

Upvotes: 1

Views: 732

Answers (2)

jfs
jfs

Reputation: 414285

subprocess module does not run the shell by default therefore the shell wildcards (globbing patterns) such as * are not expanded. You could use glob to expand it manually:

#!/usr/bin/env python
import glob
import subprocess

pattern  = 'firefox.*'
files = glob.glob(pattern) or [pattern]
subprocess.check_call(["bleachbit", "-c"] + files)

If the command is more complex and you have full control about its content then you could use shell=True to run it in the shell:

subprocess.check_call("bleachbit -c firefox.*", shell=True)

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

When shell is False you need to pass a list of args:

import subprocess
try:
    subprocess.call(["bleachbit", "-c","firefox.*"])
except:
    print ("Error.")

Upvotes: 0

Related Questions