Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python have an argc argument?

I have written the same program (open text file and display contents) in C and C++. Now am doing the same in Python (on a Linux machine).

In the C programs I used the code:

if (argc != 2) {     /* exit program */ } 

Question: What is used in Python to check the number of arguments

#!/usr/bin/python import sys try:     in_file = open(sys.argv[1], "r") except:     sys.exit("ERROR. Did you make a mistake in the spelling") text = in_file.read() print text in_file.close() 

Current output:

./python names.txt = Displays text file (correct) ./python nam = error message: stated from the sys.ext line (correct) ./python = error message: stated from the sys.ext line (wrong: want it to be a separate error message stating *no file name input*) 
like image 934
Dan1676 Avatar asked Nov 20 '11 13:11

Dan1676


People also ask

What is argv in Python?

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 run a Python script idle with arguments?

IDLE now has a GUI way to add arguments to sys. argv! Under the 'Run' menu header select 'Run... Customized' or just Shift+F5... A dialog will appear and that's it!


1 Answers

In python a list knows its length, so you can just do len(sys.argv) to get the number of elements in argv.

like image 139
sepp2k Avatar answered Oct 13 '22 23:10

sepp2k