std in and stdout

Peter Otten __peter__ at web.de
Tue Jul 11 11:31:40 EDT 2006


Juergen Huber wrote:

> how would i fix the following problem:
> 
> now i have an input file with a fix name and an output file!
> i have this two files hardcoded written in the sourcecode of this
> function!
> 
> in the future i will start this script with the command line.
> the syntax should be look like this:
> 
> Python Function | Source File    |   Output File
> -------------------------------------------------------
> fileanalyse.py    sourcefile.csv     filenalyse.txt
> 
> i will call the programm always with the commandline, that i could type in
> various filenames for the input and output files!
> 
> could anybody help me?!

Are you perhaps looking for sys.argv? The following example takes filenames
from the command line and defaults to stdin/stdout:

import sys

def analyse(instream, outstream):
    pass # your code

instream = sys.stdin
outstream = sys.stdout

if len(sys.argv) > 1:
    instream =  open(sys.argv[1])
if len(sys.argv) > 2:
    outstream = open(sys.argv[2], "w")

analyse(instream, outstream)

instream.close()
outstream.close()

Peter

PS: You might be interested in posting to the oh so quiet german-language
de.comp.lang.python



More information about the Python-list mailing list