I'm using argparse to parse the parameters, but when I get args.global, a strange error appears, I don't know where I did it wrong
...
parser.add_argument('-u','--update', action='store_true', default=None)
parser.add_argument('-g','--global', action='store_true', default=None)
args = parser.parse_args()
...
if args.update:
print(args)
print( args.global )
print( args.update )
$ python ./anpm.py -g -u
File "./anpm.py", line 67
print( args.global )
^
SyntaxError: invalid syntax
This is the error given by vscode
$ python --version
Python 3.6.8
global is a keyword in Python (as are if, while, etc.) and you cannot use these as attribute names, which means they also don't work in a NameSpace object.
More on that here:
https://docs.python.org/3/reference/lexical_analysis.html#keywords
However, you can still access these values if you need to use these names:
my_args = vars(args)
print(my_args['global'])
This works because it doesn't use the reserved word, instead it just uses a string (containing the reserved word) to access its value.
If you only need access once, or infrequently and you don't want to keep the vars() result around, you can also just:
print(vars(args)['global'])
Use getattr:
print(getattr(args, 'global'))
This would get the attribute global.
Global Explanation
Global is a reserved keyword in python that is used to declare a variable globally inside the functional scope.
Example:
def p():
global x
x=23
p()
print(x)
//returns 23
Keywords and example
A keyword can't be used as an argument or a variable in python. you can have other examples like
yield=23
return=34
pass=34
continue=23
.....
All these make an error.
Solution
Try changing the name from global to __global or _global or something like this.
Related
This is my script mytest.py.
import argparse
parser = argparse.ArgumentParser(description="Params")
parser.add_argument(
"--value")
def test(args):
print(args.value)
args = parser.parse_args()
test(args)
I want to pass argument store in variable val
val =1
!python mytest.py --value val
instead of printing 1 it print val. How to send 1 stored in variable val.
argparse always get argument as string, or list of strings on default, and what you do on your shell is irrelevant with python program. It is no wonder val is printed.
Use file that contains "1" and read that file to do what you intended to.
As jueon park said naming a variable in commandline wont work
It would create an error like the above one.If you are calling the command from any programer will work but in cmd it won't work
I'm very late for this but your python code works just fine. The problem you have is that you are not passing the arguments correctly.
For this to work first you need to correctly set the variable:
val=1
(note that the "=" must be next to both the variable name and the value)
and the you can simply use $ to get the value from the variable. So:
python mytest.py --value $val
I am trying to add a command line argument depending on some values returned by the functions. When I am not giving that argument it says:
main.py: error: argument -opp/--operator is required
When I am giving the argument it says:
main.py: error: unrecognized arguments: -opp +
Following is the piece of EDITED code (as told in one of the answers):
parser.add_argument('-z', help='Help msg', required=True)
args, unknown = parser.parse_known_args()
value = some_functions(args.z)
if value == some_particular_value:
parser.add_argument('-opp','--operator',help='Some help msg',required=True)
args = parser.parse_args()
Please help me in adding this argument. Thanks!
There are, though, a couple of mistakes in your code. Here's the corrected version:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-z', help = 'Help msg', required = True)
args, _ = parser.parse_known_args()
# value = some_functions(args.z)
if value == some_particular_value:
parser.add_argument('-opp', '--operator', help = 'Some help msg', required = True)
# args2, _ = parser.parse_known_args()
# some_function2(args2.operator)
So, let's analyse your mistakes:
Assigning instead of comparing
That's typical newbie mistake. Within a conditional operator (if, case...) you set the value instead of checking it. The difference is in amount of the = sign.
If you assign value, the condition in the operator will be always True and test will always succeed (in most of programming languages and cases).
Check this out:
a = 1
if a = 2:
print a
This may print 2 in some languages (like C or Java; using the correct syntax). Why? You've just set it! Yet, Python is smart enough to tell you about your mistake:
File "<stdin>", line 1
if a = 2:
^
SyntaxError: invalid syntax
And compare it to this:
a = 1
if a == 2:
print a
This will not print anything. Because the if test did not pass.
Assigning value instead of calling method
You want to be using the method add_argument instead of re-defining the parser variable, right?
parser = add_argument(...)
That's something like I've described above. You should be calling a method of a parser variable, not defining its new value:
parser.add_argument(...)
Re-parsing arguments is missing?
You did not show the part of the code where you check for the operator argument. Note: you should parse your arguments again, when defined a new argument:
parser.add_argument(...)
args, _ = parser.parse_known_arguments()
Then you will get a new argument in the args variable.
Using the wrong name of argument?
Again, you are missing part of code, where you check for the operator argument' value. If you are trying to access it with
args.opp # whoops...
Then you'd just get an error saying There's no argument 'opp'!, because it has its full name and should be accessed with it:
args.operator # aaah, here it is!
'args' variable name is used in my project. When I use pdb.set_trace to debug, I want to print what's in the 'args' variable. The result is far different from my expect and I figured out pdb uses 'args' as its reserved word to keep something else.
My question is how to print this 'args' variable without having to change the variable name to something not conflicting. Thanks.
I am using Python 3.4, in Windows command line console.
Python pseudo code sample:
args = dict(blah='blah'...)
... some code deal with args
def foo():
pdb.set_trace() # when traced here, I type 'args' to show what it is, but looks like it's going to print arguments of foo method, which is None.
foo()
OK. I figured it out. Using pdb command, p(args) or pp(args) should save it.
My assignment requires that "from" be used as an argument for the command line input.
p = optparse.OptionParser()
p.add_option("--from")
p.add_option("--to")
p.add_option("--file", default="carla_coder.ics")
options, arguments = p.parse_args()
print options.from
obviously, "from" is a Python keyword... is there any way to get around this? Basically, the script should be run using
file.py --from=dd/mm/yyyy --to=dd/mm/yyyy --file=file
Use the dest attribute to specify a name:
p.add_option("--from", dest="foo")
print options.foo
Use Python's getattr function:
getattr(options, 'from')
Will behave like options.from, except that the attribute name doesn't have to follow Python's usual variable naming rules (including keyword conflicts).
I do want to process a command with an argument specified by the user.
I thought about:
self.urlRegexFunc = "endswith"
self.urlRegex = ".mp3"
exec('b = attr[1].%s("%s")' % (self.urlRegexFunc, self.urlRegex)) # attr[1] is string
if b:
pass # Do Something
But I get:
SyntaxError: unqualified exec is not allowed in function 'start_a' it contains a nested function with free variables
What can I do?
You're looking for getattr().