0

Here's the scenario. I want to run a command line program from within a python script. The command would generate a file after executing which I would read into an for some further operations. I want to pass a filename as a function parameter.

 def myfunc(myinputfile,myoutputfile):
     cmd = "mycommand -i %s -o %s" %(myinputfile,myoutputfile)

I tried using subprocess.call but apparently It requires me to write commandname and arguments as seperate entries of list. Is there any other way I way to do this. Also, it is important that the command executes before proceeding as I want to read the output from file into a variable later on in the script.

Ada Xu
  • 883
  • 4
  • 12
  • 29
  • 7
    Why is Specifying command line argument as a list a problem? `subprocess.call(['mycommand', '-i', myinputfile, '-o', myoutputfile])` – falsetru Jan 06 '14 at 12:36
  • Command line quoting rules are pain in the arse. You _should_ use interface where you pass a list (like `subprocess.call`). Otherwise it will all fall apart when the path contains a funny character. And remember, in Linux it may contain _anything_ except nul byte and while Windows exclude some characters, they still don't exclude the important case of space and they don't exclude them consistently anyway. – Jan Hudec Jan 06 '14 at 12:50
  • @JanHudec Could point me to an example? – Ada Xu Jan 06 '14 at 12:54
  • Example of what? Examples of using `subprocess.call` are in the already linked answer. Examples of weird filenames? It's usually enough to have space in the path. You can have quote there too so simply quoting the argument won't do. – Jan Hudec Jan 06 '14 at 18:42

2 Answers2

1

Unless you are using shell=True, you need to pass a list of arguments to subprocess:

def myfunc(myinputfile,myoutputfile):
    cmd = ['mycommand', '-i', myinputfile, '-o', myoutputfile]

This, incidentally, makes it much easier to use variable values as arguments..

Martijn Pieters
  • 889,049
  • 245
  • 3,507
  • 2,997
0

if you want call a shell command i suggest:

    d = dict(os.environ.copy()) #copy enviroment
    cmd = "mycommand -i %s -o %s" %(myinputfile,myoutputfile)
    p = subprocess.Popen(cmd, shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.STDOUT,env=os.environ,cwd=PATHWHEREYOUHAVEACOMMAND,close_fds=True)

if you want open a Terminal and run command:

    d = dict(os.environ.copy())
    cmd4="mycommand -i %s -o %s" %(myinputfile,myoutputfile)
    cmd="gnome-terminal --working-directory=%s --title='your title' --command='%s' " % (yourpath,cmd4)
    p = subprocess.Popen(cmd, shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.STDOUT,env=os.environ,cwd=PATHWHEREYOUHAVEACOMMAND,close_fds=True)   
archetipo
  • 529
  • 3
  • 9