- How to check if the parameter exist in python
- 6 Answers 6
- Checking if sys.argv[x] is defined
- Check if sys.argv are defined inside a function
- 2 Answers 2
- How to use sys.argv in python to check length of arguments so it can run as script?
- 5 Answers 5
- validating sys.argv[] arguments in python [closed]
- 2 Answers 2
How to check if the parameter exist in python
I would like to create a simple python script that will take a parameter from the console, and it will display this parameter. If there will be no parameter then I would like to display error message, but custom message not something like IndexError: list index out of range Something like this:
if isset(sys.argv[1]): print sys.argv[1]; else: print "No parameter has been included"
6 Answers 6
if len(sys.argv) >= 2: print(sys.argv[1]) else: print("No parameter has been included")
For more complex command line interfaces there is the argparse module in Python’s standard library — but for simple projects taking just a couple parameters directly checking sys.argv is alright.
update as of 2019, the recomendation is to use the external library «click», as it provides very «Pythonic» ways of including complex documents in a way they are easily documented.
try: sys.argv[1] except IndexError as ie: print("Exception : ".format(ie))
import sys try: print sys.argv[1] except IndexError: print "No parameter has been included"
import sys print sys.argv[0] # will print your file name if len(sys.argv) > 1: print sys.argv[1]; else: print "No parameter has been included"
import sys try: print sys.argv[1] except IndexError, e: print "No parameter has been included"
Just for fun, you can also use getopt which provides you a way of predefining the options that are acceptable using the unix getopt conventions.
import sys import getopt try: opts, args = getopt.getopt(sys.argv[1:], "hvxrc:s:", ["help", "config=", "section="]) except getopt.GetoptError as err: print ("Option error:", str(err)) opts=[] for op , val in opts: print ("option",op,"Argument",val) if not opts: print ("No parameter supplied")
In the above if an incorrect parameter is supplied all of the options are scrapped.
Examples of use would be:
python myprog.py -h python myprog.py --help python myprog.py -c123 python myprog.py --config=123
Checking if sys.argv[x] is defined
Some people prefer the exception-based approach you’ve suggested (eg, try: blah = sys.argv[1]; except IndexError: blah = ‘blah’ ), but I don’t like it as much because it doesn’t “scale” nearly as nicely (eg, when you want to accept two or three arguments) and it can potentially hide errors (eg, if you used blah = foo(sys.argv[1]) , but foo(. ) raised an IndexError , that IndexError would be ignored).
As long as you’re being atomic about it though, there’s nothing to worry about with try, except . Just wait to foo your argument until the else clause.
@senderle: sure, if you’re diligent about it, that’s fine. But in my experience most programmers aren’t diligent and put all the logic in the try clause… So, given that it’s no harder (and, IMO, a bit prettier), I prefer to just check the length (also, you avoid having people yell at you for using exceptions for flow control).
@David, yeah, I do see your point. I’m a bit of a try apologist, I must admit. I just feel that it sometimes expresses my intent more clearly than an if statement.
In the end, the difference between try, except and testing len(sys.argv) isn’t all that significant. They’re both a bit hackish compared to argparse .
This occurs to me, though — as a sort of low-budget argparse:
arg_names = ['command', 'x', 'y', 'operation', 'option'] args = dict(zip(arg_names, sys.argv))
You could even use it to generate a namedtuple with values that default to None — all in four lines!
Arg_list = collections.namedtuple('Arg_list', arg_names) args = Arg_list(*(args.get(arg, None) for arg in arg_names))
In case you’re not familiar with namedtuple , it’s just a tuple that acts like an object, allowing you to access its values using tup.attribute syntax instead of tup[0] syntax.
So the first line creates a new namedtuple type with values for each of the values in arg_names . The second line passes the values from the args dictionary, using get to return a default value when the given argument name doesn’t have an associated value in the dictionary.
Check if sys.argv are defined inside a function
I would like to define a function that checks whether any argv were give to a command line, otherwise would print a string or return two strings. Here is the code:
import sys def get_input(): if len(sys.argv) > 1: path_input_text = sys.argv[1] path_basic_conf = sys.argv[2] return path_input_text, path_basic_conf elif len(sys.argv) == 1: print "Takes at least two arguments" else: print "No arguments entered" return 'file.txt', 'file.xml'
It works when I give two arguments but it fails in the other two cases, i.e. the elif and else statements. How can I make it work? Should I be using the try/except statement? thanks EDIT 1 when I try 1 args only:
IndexError: list index out of range
TypeError: 'NoneType' object is not iterable
If you want to do that, your function must always return two things, or raise an error. Maybe just return sys.argv[0], None ? Or, if the program can’t continue with one argument, raise an error rather than printing it.
2 Answers 2
argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string ‘-c’. If no script name was passed to the Python interpreter, argv[0] is the empty string. (reference : https://docs.python.org/2/library/sys.html)
import sys def get_input(): if len(sys.argv) > 2: #print (sys.argv[0]) path_input_text = sys.argv[1] path_basic_conf = sys.argv[2] return path_input_text, path_basic_conf elif len(sys.argv) ==2: #print (sys.argv[0]) print ("Takes at least two arguments") return None,None else: #print (sys.argv[0]) print ("No arguments entered") return 'file.txt', 'file.xml' a,b = get_input() print (a) print (b)
D:\>python so.py 1 Takes at least two arguments None None D:\>python so.py No arguments entered file.txt file.xml D:\>python so.py 1 2 1 2
How to use sys.argv in python to check length of arguments so it can run as script?
So the thing is I want to do is if the command line length is more than 1, the program runs as a script. This is the instruction:
If no command line arguments are input, then the script enters menu mode. If more than 1 command line argument (anything other than script name) is provided during the run of the script it enters single run mode.
5 Answers 5
What is sys.arvg:
The list of command line arguments passed to a Python script. argv[0] is the script name.
import sys if __name__=="__main__": print "command arguments:", sys.argv
$ python 1.py arg1 arg2 command arguments: ['1.py', 'arg1', 'arg2'] $ python 1.py command arguments: ['1.py']
Your problem is, we have to run code by Command Line Argument and by Menu also.
When User provided the Enter Choice from the command line then use provided value to next process.
If User not provided the Enter Choice from the command line then ask User to Enter Choice from the Menu.
import sys if __name__ == '__main__': try: arg_command = sys.argv[1] except IndexError: arg_command = "" Done = False while not Done: if arg_command=="": print('\nMenu') print('C Clear All') print('L Load Encrypted File') print('Q Quit') print('----------------') print('Enter Choice>') command = raw_input('Enter Selection> ').strip()[0].upper() else: command = arg_command #- set arg value to empty to run Menu option again. arg_command = "" if command == 'C': print "In Clear All event." elif command == 'L': print "In Clear All event." elif command == "Q": break else: print "Wrong Selection."
Enter Choice given from the Command Line:
$ python 1.py C In Clear All event. Menu C Clear All L Load Encrypted File Q Quit ---------------- Enter Choice> Enter Selection> q $
$ python 1.py Menu C Clear All L Load Encrypted File Q Quit ---------------- Enter Choice> Enter Selection> l In Clear All event. Menu C Clear All L Load Encrypted File Q Quit ---------------- Enter Choice> Enter Selection> q $
validating sys.argv[] arguments in python [closed]
So here, my sys.argv[1] value will be text. I need to validate whether its text or something else. I googled and found that argparse may help me in doing this kind of test. But i was not able to understand it. Can someone help me.
here, my argument value will be text. I googled it argparse may help in validating the value. But am so new to it, so not able to understand.
That’s not what argparse if for, it’s for specifying command-line options and their associated arguments.
If you just want to check if a string matches a pattern, use a regular expression. The fact that it’s in argv is irrelevant.
2 Answers 2
Like most programming tasks, there are several ways to tackle this:
import sys import os.path def show_help(): print("Help screen. ") flag_set=False # default to off outfile="out.txt" infile="in.txt" i = 1 # 0 is the filename of the script while i < len(sys.argv): arg = sys.argv[i] i += 1 if arg == "-h" or arg == "--help": show_help() sys.exit(0) elif arg == "-f" or arg == "--flag": flag_set=True elif arg == "-o" or arg == "--outfile": outfile=sys.argv[i] # ignoring len check for brevity i += 1 elif arg == "-i" or arg == "--infile": infile=sys.argv[i] # ignoring len check for brevity # Simple parameter validation if not os.path.exists(infile): print("Input file '", infile, "' not found.") sys.exit(0) i += 1 # . for any other args you want if flag_set: print("Flag was set") print("Reading from:", infile) print("Outputting to:", outfile)
You can do any kind of validation you want with simple logic such as this.
There is no "wrong" way to do it, use whatever gets the job done for you! But do try to stick to standard flags, like -h for help, etc.