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

喜夏-厌秋 提交于 2020-07-06 13:47:05

问题


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.


回答1:


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.)



来源:https://stackoverflow.com/questions/36675515/python-how-to-parse-argv-on-the-command-line-using-stdin-stdout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!