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

2024/11/17 14:26:26

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 stuffelif sys.argv == f:#execute some stuffelse: 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.

Answer

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://en.xdnf.cn/q/71545.html

Related Q&A

Bad Request from Yelp API

Inspired by this Yelp tutorial, I created a script to search for all gyms in a given city. I tweaked the script with these updates in order to return ALL gyms, not just the first 20. You can find the g…

Python: test empty set intersection without creation of new set

I often find myself wanting to test the intersection of two sets without using the result of the intersections.set1 = set([1,2]) set2 = set([2,3]) if(set1 & set2):print("Non-empty intersection…

object has no attribute show

I have installed wxpython successfully which i verified by import wxBut when I write a code import wx class gui(wx.Frame):def __init__(self,parent,id):wx.Frame.__init__(self, parent,id,Visualisation fo…

How Does Calling Work In Python? [duplicate]

This question already has answers here:Does Python make a copy of objects on assignment?(5 answers)How do I pass a variable by reference?(40 answers)Why can a function modify some arguments as percei…

Python: Sklearn.linear_model.LinearRegression working weird

I am trying to do multiple variables linear regression. But I find that the sklearn.linear_model working very weird. Heres my code:import numpy as np from sklearn import linear_modelb = np.array([3,5,7…

Implementation of Gaussian Process Regression in Python y(n_samples, n_targets)

I am working on some price data with x = day1, day2, day3,...etc. on day1, I have lets say 15 price points(y), day2, I have 30 price points(y2), and so on.When I read the documentation of Gaussian Proc…

Converting a list of points to an SVG cubic piecewise Bezier curve

I have a list of points and want to connect them as smoothly as possible. I have a function that I evaluate to get these points. I could simply use more sampling points but that would only increase the…

Python Class Inheritance AttributeError - why? how to fix?

Similar questions on SO include: this one and this. Ive also read through all the online documentation I can find, but Im still quite confused. Id be grateful for your help.I want to use the Wand class…

Is it possible to display pandas styles in the IPython console?

Is it possible to display pandas styles in an iPython console? The following code in a Jupyter notebookimport pandas as pd import numpy as npnp.random.seed(24) df = pd.DataFrame({A: np.linspace(1, 10,…

HEAD method not allowed after upgrading to django-rest-framework 3.5.3

We are upgrading django-rest-framework from 3.1.3 to 3.5.3. After the upgrade all of our ModelViewSet and viewsets.GenericViewSet views that utilize DefaultRouter to generate the urls no longer allow …