Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to parse argv on the command line using stdin/stdout?

I'm new to programming. I looked at tutorials for this, but I'm just getting more confused. But what I'm trying to do is use stdin and stdout to take in data, pass it through arguments and print out output results.

So basically,on the command line, the user will input the and an argument.

The arguments are:

i = sys.argv [1]

f = sys.argv [2]

w = sys.argv [3]

Then using if/else the program will execute some stuff based on which argument chosen above.

i.e: On the command line the user will enter the script name and f (for sys.argv[2:2])

$ test.py f

.

if sys.argv == i:
     #execute some stuff

elif sys.argv == f:
      #execute some stuff

else: 
     sys.argv == w
     #execute some stuff

With stdin/stdout how can I create this switch where the program executes one piece of the code based on which argv is chosen? Any input will be greatly appreciated.

like image 927
brazjul Avatar asked Apr 17 '16 10:04

brazjul


1 Answers

It looks like you are a bit confused about sys.argv. It is a list of the parameters you gave to your program when you started it. So if you execute python program.py f it will be ["program.py", "f"]. If you execute it as python program.py f w i it will be ["program.py", "f", "w", "i"]. So the code you showed:

i = sys.argv[1]
f = sys.argv[2]
w = sys.argv[3]

will throw an exception if you call the program with less than 3 parameters.

There are some libraries to help you with parsing parameters like argparse or click. But for simple cases just using sys.argv is probably easier.

It looks like you want your program to operate in three modes: i, f, and w.

if len(sys.argv) > 2:
    print("Please only call me with one parameter")
    sys.exit()

if sys.argv[1] == "f":
    #do some stuff
elif sys.argv[1] == "i":
    #do some other stuff
elif sys.argv[1] == "w":
    #do some more other stuff
else:
    print("Only accepted arguments are f, i and w")
    sys.exit()

You can write to stdout via print or sys.stdout.write() where the first one will add a linebreak to each string you input.

If you want the user to interactively input something, you should use input() (raw_input() in python2. There input() evaluates the statement as python code which you almost always don't want).

If you want to do something with lots of data you are probably best off if you pass a path to your program and then read a file in. You can also use stdin via sys.stdin.read() but then you want to pass something in there either via a pipe some-other-program | python program.py f or reading a file python program.py f < file.txt. (Theoretically you could also use stdin to read interactive data but don't do that, use input instead.)

like image 179
syntonym Avatar answered Oct 20 '22 06:10

syntonym