BaRud
BaRud

Reputation: 3218

call linux command with variable argument from python

I am trying to execute a program from python2x.

In terminal, the job will run as:

mpirun -np 8 ~/WORK/scf Fe_SCF.inp > Fe_SCF.out

Where Fe_SCF.* are input and output in the CWD.

Now, I am trying to run this piece from python script. Since, I have defined them as variable and tried to call as:

call(["mpirun -np 8 ~/WORK/scf", scfin,  scfout])

Giving Error:

  File "./triolith.py", line 38, in <module>
        call(["mpirun -np 8 ~/WORK/scf", scfin,  scfout])
      File "/usr/lib64/python2.7/subprocess.py", line 522, in call
        return Popen(*popenargs, **kwargs).wait()
      File "/usr/lib64/python2.7/subprocess.py", line 710, in __init__
        errread, errwrite)
      File "/usr/lib64/python2.7/subprocess.py", line 1335, in _execute_child
        raise child_exception
    OSError: [Errno 2] No such file or directory

Using real filename does not solve the problem either:

 call(["mpirun -np 8 ~/WORK/scf", "Fe_SCF.inp",  "Fe_SCF.out"])

Which gives error:

File "./triolith.py", line 38, in <module>
    call(["mpirun -np 8 ~/WORK/scf", "Fe_SCF.inp",  "Fe_SCF.out"])
  File "/usr/lib64/python2.7/subprocess.py", line 522, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib64/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

I have checked and can confirm, using os.system is working with "Real" filename, but not with variable name as:

 os.system("mpirun -np 8 ~/WORK/scf scfin" )

So, using either of two method, how can I call the program with a variable name as input and output?

Upvotes: 0

Views: 835

Answers (2)

hd1
hd1

Reputation: 34677

call takes a list, hence your first example should be:

cmd = ['/absolute/path/to/mpirun', '-np', '8', '~WORK/scf', var_1]
call(cmd, stdout=var_2, stderr=STDOUT)

Upvotes: 2

Henry
Henry

Reputation: 1686

In your latter example using the OS module, you should be able to do:

os.system("mpirun -np 8 ~/WORK/scf "+ var_name)

To run your function call.

For multiple variables,d o:

os.system("mpirun -np 8 ~WORK/scf " + var_1 + " " + var_2)

Upvotes: 1

Related Questions