Take the 2-minute tour ×

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
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: nameinfileis 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 which includes some Popen examples and two or three pertinent questions here , here and here .

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??

share|improve this question

1 Answer 1

up vote 0 down vote accepted

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:


using subprocess module:

import subprocess

with open("inputfile.txt", "rb") as infile, open("outfile.txt", "wb") as outfile:
                           stdin=infile, stdout=outfile)
share|improve this answer
i like more the second approach you proposed using the subprocess module. it is more simple for me and apparently it works great! thanks –  user1834437 Jul 17 '13 at 15:12

Your Answer

