March 30th, 2004, 01:48 AM
distinguishing between two forms of input
how can i distinguish between two form of input such as stdin and command line
python p.py < file.txt
python p.py file.txt
i tried if/else statements based on the presence of < in sys.argv but it doesn't seem to be detecting <... moreover, i dont' know want to do it based on the number of arguments (1 argument for stdin and 2 arguments for command line) as i may do it this way
cat file.txt | python p.py
i also may include other option after
python p.py < file.txt -d whatever -1 wohoo
and one more question...
how can output a file to a directory other than the current directroy... i'm pretty it is in th os module but i can't seem to find it...
file = open("input.txt", "w")
how can i output input.txt to another directory other than my current working directory...
March 30th, 2004, 02:56 AM
< file.txt will not appear as a command line item because it is a directive to the shell. It is telling the shell to send the contents of the file to stdin of the program p.py.
I suggest you do in fact check for a filename being provided (it will be argv in your example). Or you could include a command line option for your program to read from stdin (e.g.
python p.py --stdin). Have a look at the getopts module.
To write to a file not in you current directory you can specify the absolute or relative path in the file command:
This path format works on Windows too because Python will automatically convert the '/' to '\' for you
March 30th, 2004, 03:29 AM
thanks a lot
March 30th, 2004, 07:36 AM
I don't think it's the case that it converts it, just that Windows handles either slash as a path separator.
Originally Posted by Grim Archon
Also, optparse is a more advanced module than getopt (note that it doesn't have an s on the end) and generally nicer to work with, IMO.