Python Menu

Command-Line Arguments in Python


Till now, we have taken input in python using raw_input() or input(). There is another method that uses command line arguments. The command line arguments must be given whenever we want to give the input before the start of the script, while on the other hand, input() is used to get the input while the python program / script is running.

How do I use it?

To use it, you will first have to import it (import sys) The first argument, sys.argv[0], is always the name of the program as it was invoked, and sys.argv[1] is the first argument you pass to the program. It's common that you slice the list to access the actual command line argument:

The sys module also provides access to any command-line arguments via sys.argv. Command-line

arguments are those arguments given to the program in addition to the script name on invocation.

  • sys.argv is the list of command-line arguments
  • len(sys.argv) is the number of command-line arguments.

To use argv, you will first have to import it (import sys) The first argument, sys.argv[0], is always the name of the program as it was invoked, and sys.argv[1] is the first argument you pass to the program. It's common that you slice the list to access the actual command line arguments.


Example:
# file name "cmdarg.py"
import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)
print(program_name)
print(arguments)
print("Number of arguments ",count)
Output:
python cmdarg.py 45 56
cmdarg.py
['45', '56']
Number of arguments  2

Example Program:

Aim: Python Program to merge two files using command line argument.

myfile.txt
function open() to open a file.
method read() to read a file.
Python is the modern day language.
myfile1.txt
Python supports Files 
python supports Strings.
Example:
# file name "fileprg.py"
from sys import argv
if len(argv)==4:
	try:
		fp1=open(argv[1],"r")
		fp2=open(argv[2],"r")
		fp3=open(argv[3],"w+") #w+ mode create a file if file doesn’t exist.
		for i in fp1:
			fp3.write(i) # write content from first file to third file
		for i in fp2:
			fp3.write(i) # write content from second file to third file
		print("Two files merged successfully")
		print("Content in ",argv[3])
		fp3.seek(0,0) # to move file point cursor to starting of file
		for i in fp3:
			print(i,end=" ")
		fp1.close()
		fp2.close()
		fp3.close()
	except Exception:
		print("Enter valid filenames")
Output: Case 1
>>python fileprg.py myfile.txt myfile1.txt myfile2.txt

Two files merged successfully
Content in  myfile2.txt

function open() to open a file.
method read() to read a file.
Python is the modern day language
Python supports Files
python supports Strings.
Output: Case 2
>>python fileprg.py abc.txt myfile1.txt myfile2.txt
Enter valid filenames

In case 2 we had an exception because abc.txt file does not exist


Next Topic :File System in Python