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
Related
In a shell script I have:
/usr/local/bin/pybot --variablefile variables.py:$var1:$var2 test_cases.tsv
inside variables.py how can I access var1 and var2 arguments?
I have tried:
import sys
var1 = sys.argv[1]
var1 = sys.argv[2]
it seems like this doesn't work.
For you to access the variables, your variable file must define the function get_variables, which will be given the arguments passed from the command line. This function needs to return a dictionary where the keys are the robot variable names.
For example:
def get_variables(arg1, arg2):
variables = {
"var1": arg1,
"var2": arg2
}
return variables
If your variable file is based on a class, the class needs to have the get_variables method.
For example:
# variables.py
class variables(object):
def get_variables(self, arg1, arg2):
variables = {
"var1": arg1,
"var2": arg2
}
return variables
When you do the above, your test will have two variables set: ${var1} and ${var2} which will have the values that were passed via the --variablefile argument.
Here is a test that can be used to verify the above:
# example.robot
*** Test cases ***
Example
should be equal ${var1} hello
should be equal ${var2} world
Here is how to run the test in order for it to pass:
$ var1=hello
$ var2=world
$ /usr/local/bin/pybot --variablefile variables.py:$var1:$var2 example.robot
Of course, var1 and var2 are completely arbitrary. You can pass raw strings, too:
$ /usr/local/bin/pybot --variablefile variables.py:hello:world example.robot
Passing arguments is described in the user guide section titled Getting variables from a special function
sys reads the arguments fron the command line, as they appears to it:
sys.argv[0] contains the script name
sys.argv[1], the first argument (whatever it is)
sys.argv[2], the second, and so on.
You should use argparse, it helps to build comprehensive CLIs. A nice tutorial exists on the Python website.
You seem to make assumptions about how the arguments are parsed which are not true. Here's how these arguments are passed from the shell to Python:
sys.argv[0] is /usr/local/bin/pybot
sys.argv[1] is --variablefile
sys.argv[2] is variables.py:$var1:$var2 where the values of the shell variables var1 and var2 are substituted.
sys.argv[n] is test_cases.tsv
The last one is [n] because without quotes around the argument, sys.argv[2] might actually be split into multiple values. For example, if var1 contains = foo * bar= then actually
sys.argv[2] is variables.py:=
sys.argv[3] is foo
sys.argv[4..n-2] is a list of files in the current directory, and
sys.argv[n-1] is =bar:$var2 where similar further processing for the value of var2 may take place.
There are Python argument parsing modules which assign further semantics e.g. to arguments which start with a dash (these will be interpreted as options) but by itself, Python does no such thing. If that's what you want, maybe look at argparse or one of its replacements; but you still need to understand how the basic mechanics work. A common arrangement is to avoid internal structure in arguments, and instead require the user to pass each value as a separate argument -- so perhaps
--variablefile variables.py --variablefile "$var1" --variablefile "$var2"
with quoting to prevent the shell from attempting to perform whitespace tokenization and wildcard expansion on the variable values, and then probably in your script an argparse definition which says to merge multiple option arguments into a list.
parser = argparse.ArgumentParser()
parser.add_argument('--variablefile', action='append')
How do I pass in parameters to Luigi? if I have a python file called FileFinder.py with a class named getFIles:
class getFiles(luigi.Task):
and I want to pass in a directory to this class such as:
C://Documents//fileName
and then use this parameter in my run method
def run(self):
how do I run this in command line and add the parameter for use in my code? I am accustomed to running this file in command line like this:
python FileFinder.py getFiles --local-scheduler
What do I add to my code to use a parameter, and how do I add that parameter to the command line argument?
Also, as an extension of this question, how would I use multiple arguments? or arguments of different data types such as strings or lists?
As you have already figured out, you can pass arguments to luigi via
--param-name param-value
in the command line. Inside your code, you have to declare these variables by instantiating the Parameter class or one of it's subclasses. The subclasses are used to tell luigi if the variable has a data-type that is not string. Here is an example which uses two command line arguments, one Int and one List:
import luigi
class testClass(luigi.Task):
int_var = luigi.IntParameter()
list_var = luigi.ListParameter()
def run(self):
print('Integer Param + 1 = %i' % (self.int_var + 1))
list_var = list(self.list_var)
list_var.append('new_elem')
print('List Param with added element: ' + str(list_var))
Note that ListParams actually get converted to tuples by luigi, so if you want to do list operations on them, you have to convert them back first (This is a known issue, but doesn't look like it will be fixed soon).
You can invoke the above module from the command line like this (i have saved the code as a file called "testmodule.py" and made the call from inside the same directory):
luigi --module testmodule testClass --int-var 3 --list-var '[1,2,3]' --local-scheduler
Note here that for variables containing a _, this has to be replaced by -.
The call yields (along with many status messages):
Integer Param + 1 = 4
List Param with added element: [1, 2, 3, 'new_elem']
So I think this works, in the code I added:
fileName = luigi.Parameter()
if i run this in the command line:
python FileFinder.py getFiles --local-scheduler --getFiles-fileName C://Documents//fileName
but if anyone has any advice on parameters of different types and how to use them, especially numbers and lists, please let me know.
Adding to Toterich's answer.
While passing a list of string arguments as a ListParameter():
python file_name.py --local-scheduler TaskName --arg '["a","b"]'
The string arguments must be enclosed in double-quotes and not single quotes otherwise it'll give a JSONParsing error.
in command line if I run my program
python parse.py config=abc.txt factor_date=20151001 like this
I want the position of argument will be fixed. That means if I pass argument like below
python parse.py factor_date=20151001 config=abc.txt
it has to show error.
import sys
config_file=sys.argv[1]
factor_date = sys.argv[2]
argstring=""+config_file+" "+factor_date+""
arg_list = argstring.split(' ')
input={}
for arg in arg_list:
#x=arg.split("--")
key,val=arg.split("=")[0],arg.split("=")[1]
if key == "config":
input[key]=val
if key =="factor_date":
input[key]=val
print input
You can have a look at click. It let's you create command line interfaces pretty much effortlessly. It's bases on using decorators.
You should have a look at argparse. Your use case is for positional arguments. If you specify the name of the argument (optional arguments with argparse) then it does not make sense to force a specific order.
Still, when using positional arguments one could call the program with worng arguments, you will have to check by yourself the values provided by the user. However, you can force a type and it will automagically convert the strings, which in the case you describe would solve the problem.
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).
Using python optparse.py, is there a way to work out whether a specific option value was set from the command line or from the default value.
Ideally I would like to have a dict just like defaults, but containing the options actually supplied from command line
I know that you could compare the value for each option with defaults, but this wouldn't distinguish a value was passed through command line which matched the default.
Thanks!
EDIT
Sorry my original phrasing wasn't very clear.
I have a large number of scripts which are called from batch files. For audit purposes, I would like to report on the options being passed, and whether they are passed from command line, default, or some other means, to a log file.
Using defaults you can tell whether an option matches a default value, but that still doesn't tell you whether it was actually supplied from command line. This can be relevant: if an option is passed from command line and agrees with the default, if you then change the default in the code the script will still get the same value.
To me it would feel quite natural to have an equivalent to defaults, containing the values actually supplied.
To make the question concrete, in this example:
>>> sys.argv = ['myscript.py','-a','xxx']
>>> import optparse
>>> parser = optparse.OptionParser()
>>> parser.add_option('-a', default = 'xxx')
>>> parser.add_option('-b', default = 'yyy')
How do I know that option a was passed from command line. Is the only way to parse the command line manually?
(I know this is a fairly minor point, but I thought it would be worth asking in case I'm missing smthing on optparse)
Thanks again
Instead of the below boilerplate code:
opts, args = parser.parse_args()
if you use the below code, you will have an additional values object opts_no_defaults with options that were explicitly specified by the user:
opts_no_defaults = optparse.Values()
__, args = parser.parse_args(values=opts_no_defaults)
opts = Values(parser.get_default_values().__dict__)
opts._update_careful(opts_no_defaults.__dict__)
At the end, opts should be identical as in the initial boilerplate code.
print opts_no_defaults.__dict__
print opts.__dict__
for opt in parser._get_all_options():
if opt.dest:
print "Value of %s: %s" % (opt._long_opts[0], getattr(opts, opt.dest))
print "Is %s specified by user? %s" % (opt._long_opts[0], hasattr(opt_no_defaults, opt.dest))
Not knowing you code is impossible to give the better answer, but...
simply don't pass defaults to the parser and check for None values. A None value is a default for optparse lib so you can retrieve your own default and act as usually;
extend optparse to specialize it.
I don't know your program but usually it is not a good design changing behavior when the configuration is the same.
def is_opt_provided (parser, dest):
if any (opt.dest == dest and (opt._long_opts[0] in sys.argv[1:] or opt._short_opts[0] in sys.argv[1:]) for opt in parser._get_all_options()):
return True
return False
Usage:
parser = OptionsParser()
parser.add_option('-o', '--opt', dest='opt_var', ...)
if is_opt_provided(parser, 'opt_var'):
print "Option -o or --opt has been provided"
It would be great if Python maintainers included the suggested function to OptionParser class.