tags:

views:

61

answers:

3

Hi,

Trying to execute shell command in background using pythons commands module

>>>import commands
>>>output = commands.getstatusoutput("find / > tmp.txt &")
   sh: Syntax error: ";" unexpected

Can anyone explain what is wrong with the syntax ? How should it be executed then ?

Tazim.

+1  A: 

I'm not aware of a way to directly execute a command in background like that. Particularly, it's because commands module does not run the command through bash, which is what usually parses the ampersand.

You should do a fork/exec call from the os module to run things in background.

ivans
+5  A: 

According to the getstatusoutput documentation, commands.getstatusoutput(cmd) is executed as

{ cmd  ; } 2>&1

so your command is run as if it was

{ find / > tmp.txt & ; } 2 >& 1

and the ; is not valid after the & in such a command.

You should use the subprocess module to simulate the old-style os.spawn commands.

Try

subprocess.Popen("find / > tmp.txt", shell=True)
Blair Conrad
+1 for mentioning the subprocess module. I'd remove the rest of the flibbify-flabiddy (or at least make a note) because it's strictly *nix specific. There are ways to use the subprocess module to process stdin stdout stderr in python in a cross platform manner.
Evan Plaice
+1  A: 

Try to create a daemon to run your process in background.

aeby