0

I am trying to write python code which will execute following steps in cmd terminal in linux machine

cd /path/to/destination/
3dAFNItoNIFTI *epi*

i tried calling subprocess.call two times, once to cd and then impleemnt that command. but it doesnt seem to work.

Is there a way to call two line inux command code using subprocess?

Thanks!

3 Answers3

6

cding in one subprocess call will not affect another, since they are executed in different processes. You want to use os.chdir:

with os.chdir("/path/to/destination"):
    subprocess.call(cmd)

Not all versions of Python support with os.chdir; if yours doesn't, you can do this:

old_dir = os.getcwd()
os.chdir("/path/to/destination")
subprocess.call(cmd)
os.chdir(old_dir)
mipadi
  • 398,885
  • 90
  • 523
  • 479
  • getting an error... `import os >>> import subprocess >>> with os.chdir("/Users/sdb99/E1000"): ... subprocess.call("3dAFNItoNIFTI /Users/sdb99/E1000/*3d_scan_2*orig") ... Traceback (most recent call last): File "", line 1, in AttributeError: __exit__` @mipadi – learnningprogramming Jan 07 '16 at 20:50
  • @tryeverylanguage: What version of Python are you using? – mipadi Jan 07 '16 at 21:50
  • 1
    @tryeverylanguage: I updated my answer to avoid using `with`, which I think is the problem. – mipadi Jan 07 '16 at 22:36
0
import commands
my_work = "cd /path/to/destination/ ; 3dAFNItoNIFTI *epi*"
status, output = commands.getstatusoutput(my_work)

getstatusoutput returns the return status (of the last bash command) and the returned output (from stdout)

mgc
  • 5,223
  • 1
  • 24
  • 37
Prune
  • 76,765
  • 14
  • 60
  • 81
  • Apparently this didnt help. the command didnt execute.. didnt get any error too but output file is not seen – learnningprogramming Jan 07 '16 at 20:44
  • I submitted an edit to the code to correct a mistake : `my_work` have to be passed in argument to `getstatusoutput`. Anyway this should only work on python 2.* as I guess there is no more `commands` module in python 3. – mgc Jan 07 '16 at 21:07
  • `command` is working fine in linux terminal but when called uisng subprocess it gives error `/bin/sh: cd/Users/sdb99/E1000 | 3dAFNItoNIFTI *3d_scan_2*orig*: No such file or directory 127` any idea what might have caused this? @Prune – learnningprogramming Jan 07 '16 at 21:39
0

got the way to do it:

import subprocess

command = command = """cd /path/to/destination | ls -al | pwd"""
b = subprocess.call(command, shell=True)
  • Correct idea, but wrong implementation. Replace the first `|` with either `&` or `;` depending on whether you want a failure in the `cd` command to stop the whole pipeline or not, respectively. Piping the output of `cd` to `ls` *happens* to work here, but more or less by accident. – Warren Young Jan 07 '16 at 21:56