Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple arguments with stdin in Python

I have a burning question that concerns passing multiple stdin arguments when running a Python script from a Unix terminal. Consider the following command:

$ cat file.txt | python3.1 pythonfile.py

Then the contents of file.txt (accessed through the "cat" command) will be passed to the python script as standard input. That works fine (although a more elegant way would be nice). But now I have to pass another argument, which is simply a word which will be used as a query (and later two words). But I cannot find out how to do that properly, as the cat pipe will yield errors. And you can't use the standard input() in Python because it will result in an EOF-error (you cannot combine stdin and input() in Python).

like image 940
lennyklb Avatar asked Sep 08 '13 17:09

lennyklb


Video Answer


2 Answers

I am reasonably sure that the stdin marker with do the trick:

cat file.txt | python3.1 prearg - postarg

The more elegant way is probably to pass file.txt as an argument then open and read it.

like image 126
Steve Barnes Avatar answered Sep 23 '22 09:09

Steve Barnes


The argparse module would give you a lot more flexibility to play with command line arguments.

import argparse

parser = argparse.ArgumentParser(prog='uppercase')
parser.add_argument('-f','--filename',
                    help='Any text file will do.')                # filename arg
parser.add_argument('-u','--uppercase', action='store_true',
                    help='If set, all letters become uppercase.') # boolean arg
args = parser.parse_args()
if args.filename:                       # if a filename is supplied...
    print 'reading file...'
    f = open(args.filename).read()
    if args.uppercase:                  # and if boolean argument is given...
        print f.upper()                 # do your thing
    else:
        print f                         # or do nothing

else:
    parser.print_help()                 # or print help

So when you run without arguments you get:

/home/myuser$ python test.py
usage: uppercase [-h] [-f FILENAME] [-u]

optional arguments:
  -h, --help            show this help message and exit
  -f FILENAME, --filename FILENAME
                        Any text file will do.
  -u, --uppercase       If set, all letters become uppercase.
like image 20
dmvianna Avatar answered Sep 25 '22 09:09

dmvianna