Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python and sys.argv

Tags:

python

if len(sys.argv) < 2:     sys.stderr.write('Usage: sys.argv[0] ')     sys.exit(1)   if not os.path.exists(sys.argv[1]):     sys.stderr.write('ERROR: Database sys.argv[1] was not found!')     sys.exit(1) 

This is a portion of code I'm working on. The first part I'm trying to say if the user doesn't type python programname something then it will exit.

The second part I'm trying to see if the database exists. On both places I'm unsure if I have the correct way to write out the sys.argv's by stderr or not.

like image 714
Tyler Avatar asked Jun 11 '09 19:06

Tyler


People also ask

What is SYS argv in Python?

sys. argv is a list in Python that contains all the command-line arguments passed to the script. It is essential in Python while working with Command Line arguments.

How do I use SYS argv 1 in Python?

len()- function is used to count the number of arguments passed to the command line. Since the iteration starts with 0, it also counts the name of the program as one argument. If one just wants to deal with other inputs they can use (len(sys. argv)-1).


1 Answers

BTW you can pass the error message directly to sys.exit:

if len(sys.argv) < 2:     sys.exit('Usage: %s database-name' % sys.argv[0])  if not os.path.exists(sys.argv[1]):     sys.exit('ERROR: Database %s was not found!' % sys.argv[1]) 
like image 166
Marius Gedminas Avatar answered Sep 24 '22 06:09

Marius Gedminas