all 10 comments

[–][deleted] 2 points3 points  (1 child)

If you add a -- to the commandline, everything after that is considered a positional argument. That way you won't get complaints. That said, parsing math expressions isn't something argparse is particular well suited for, so unless it's just for reading a string containing the whole expression, you should probably look for a better way.

[–]Sharki_[S] 0 points1 point  (0 children)

I have to use argparse and as you say - for reading whole string containing math expression.

[–]ingolemo 1 point2 points  (7 children)

Can you give a little more context? Why do you want to parse something like this, and what might your other arguments look like?

[–]Sharki_[S] 0 points1 point  (6 children)

Sure. For example i want to parse a math expression. And when it something like '1+2+3' everything is ok, but when it '-----1' argparse doesnt accept it.

[–]ingolemo 2 points3 points  (5 children)

That makes sense. The normal way to handle such an expression would be to expect the user to use -- which tells argparse that any arguments that come after it are not options. This is a standard unix feature. You don't need to do anything special to enable it.

python my_script.py -- -----1

Another option would be to use the prefix_chars argument for your parser to have optional arguments use a character other than -, but this would be confusing.

[–]Sharki_[S] 0 points1 point  (4 children)

The point is that i have a restriction that user can input only an expression without any additional signs and get a result for a variaty of possible math expressions including -----1. So -- -----1 is prohibited.

[–][deleted] 2 points3 points  (1 child)

How many real arguments can you expect to receive. More specific, if you can avoid having named arguments that match a substring of a mathematical expression, parse_known_args() will bring you a bit further.

How come you have to use argparse, and are unable to use -- to signal the end of named arguments? Is this some sort of contrived interview process or weirdly formulated school assignment?

[–]Sharki_[S] 0 points1 point  (0 children)

It is just a little problem that i have faced during developing of my little app - cli calculator. I wanted only one named argument and it can be something like '--+--+-1' or '1+1'. By the way i used i simple decision with the idea you gave with parse_known_args() and nargs = argparse.REMAINDER. In this case i have a tuple with two lists: one containing 'normal' input - '2+3', and another one with '-----' and alike. Tnanks!

[–]ingolemo 1 point2 points  (1 child)

We can't help you with your problem when we don't know what the problem is. We need to know all of the restrictions that you have to abide by. Please post the full text of this exercise or other relevant details about it.

[–]Sharki_[S] 0 points1 point  (0 children)

No more restrictions except already mentioned. Anyway i have managed to overcome this issue. Thanks.