4

Hi I am quite new to Python and I am trying to call a subprocess from another Python Script using subprocess.call. But my arguments are variable names. So, should I use subprocess.call or subprocess.popen ?

I want to execute the following command from another python script:

python npp.python -i fname -o fname+"out" -l fname+"log" -e excplist -i ignorelist 

So, should I do

subprocess.Popen(['python', 'npp.python', '-i', fname , 'o', fname+"out", '-l', fname+"log", '-e', excplist,'-i',ignrlist]).communicate()

I am not able to call the other program by doing so. Any suggestions on what I am doing wrong ?

wanab_geek
  • 333
  • 2
  • 6
  • 12

1 Answers1

0

PJust for reference. A really simple way to do something like this is simply defining the command beforehand and than transforming it into a list of arguments.

command = "python npp.python -i {file} -o {file}.out -l {file}.log -e {excep} -i {ignore}".format(file=pipe.quote(fname), excep=exceptlist, ignore=ignorelist)

subprocess.call(shlex.split(command)) # shlex.split is safer for shell commands than the usual split
# or popen if the return code isn't needed
subprocess.Popen(shlex.split(command))

This way it is harder to make mistakes when writing your command in list form.

cwoebker
  • 3,158
  • 5
  • 27
  • 43
  • 1
    If you need a list, create a list. Don't start with a string and convert it to a list. – Bryan Oakley Jun 29 '13 at 13:19
  • Do you mind elaborating on why one shouldn't do the above. I understand that it adds an extra step to the program, but it makes looking at the command a lot nicer. In my opinion it easily solves the problem of making stupid syntax mistakes when creating the command in list form, especially if its long like in the OPs case. Many others are doing it the same way: http://stackoverflow.com/questions/4091242/subprocess-call-requiring-all-parameters-to-be-separated-by-commas – cwoebker Jun 29 '13 at 15:12
  • `shlex.split()` is convenient for splitting dynamic strings, but ifsthe command is a static string, splitting it yourself when you write the code is more economical. It's not a huge inefficiency, though; but gluing it together from parts only to then pass it to `shlex.split()` is obviously a bit reckless. The bigger problem is perhaps that you are obscuring what you end up executing. – tripleee Oct 12 '21 at 08:07