Python sub process call
Question: What i am trying to accomplish in a few words is this: change directories and
call script from shell.

So far so good i have managed to change directories with `os.chdir()` .

However i haven't been able to understand how to syntax the second part of the
given task. Specifically, the command that i want to invoke is this one
`/path-to-dir-of-the-script/script<inputfile.txt>outfile.txt` and to my eyes
at least the problem is that the input file (and evidently the output file
that do not exist but will be generated by the script) are in two different
directories.

So by trying the following (`ls` and `print` are for debugging and supervising
purposes more or less) along with various modifications i am always getting an
error. Either SyntaxError or the system cannot find the two files, etc.

    
    
    import subprocess
    import os
    import sys
    
    subprocess.call(["ls"]) #read the contents of the current dir
    print
    os.dir('/path-to-dir')
    subprocess.call(["ls"])
    print
    in_file = open(infile.txt) #i am not sure if declaring my files is a necessity.
    out_file = open (outfile.txt)
    com = /path-to-dir-of-the-script/script
    process = subprocess.call([com], stdin=infile.txt, stdout=outfile.txt)
    

This is the last implementation of it which generates: `NameError:
name`infile`is not defined`

I am sure there are more than one errors in my approach (except form my
syntax) and i would probably have to study more. So far i ve taken a look in
the [doc](http://docs.python.org/2/library/subprocess.html) which includes
some `Popen` examples and two or three pertinent questions
[here](http://stackoverflow.com/questions/15205597/use-python-subprocess-
module-like-a-command-line-simulator) ,
[here](http://stackoverflow.com/questions/6046779/explain-example-from-python-
subprocess-module) and
[here](http://stackoverflow.com/questions/17571217/python-sub-process-call-
with-filename-variable) .

In case i didn't made myself clear some notes :

Script and files are not on the same level. The command is valid and works
flawless when it comes down to it. Moving either the files, either the script
into the same level won't work.

Any suggestions??


Answer: Use quotes to create a string in Python e.g.:

    
    
    com = "/path-to-dir-of-the-script/script"
    

You could use `cwd` argument to run a script with a different working
directory e.g.:

    
    
    subprocess.check_call(["ls"]) # read the contents of the current dir
    subprocess.check_call(["ls"], cwd="/path-to-dir") 
    

To emulate the bash command:

    
    
    $ /path-to-dir-of-the-script/script < inputfile.txt > outfile.txt
    

using `subprocess` module:

    
    
    import subprocess
    
    with open("inputfile.txt", "rb") as infile, open("outfile.txt", "wb") as outfile:
         subprocess.check_call(["/path-to-dir-of-the-script/script"],
                               stdin=infile, stdout=outfile)
    

