Reputation:
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
infileis 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??
Upvotes: 1
Views: 543
Reputation: 414865
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)
Upvotes: 2