Skip to main content
Python 3

Working with simple script arguments in Python

By April 17, 2013No Comments

Our script to create user accounts is coming along. We left off last time having been able to create the user with an expiry date. The downside was that the user was hard coded into the file. Moving on we want at least the username to be able to be passed in to the script at runtime as an argument. In other words : ./user.py fred

It would also be nice if we could provide multiple arguments such as : ./user.py fred joe. This creates two users in one go. These are not difficult to do and we shall look at the solution in this tutorial using Python 3 on Linux.

We already have the sys.module imported, we used it before in sys.exit. The sys module has an array property sys.argv, the first element of the array, sys.argv[0] is always populated and is the script itself. We can use this in error messages, “You have to be root to run ” + sys.argv[0] then could return the message to the user You have to be root to run ./user.py. To ensure that the user has entered a user to create we can test for the elements in the array or the arrary length: if len(sys.argv)==1: , if the array is just one item then this will be the script name and no use, so we need at least 2 items in the array for it to be of use. To create the user now we would modify the code to:

os.system("useradd -m -p "+encPassword+" -e "+expire+" " + sys.argv[1]).

If we would like to create more than one user we can use a for loop to iterate though the array:

	for u in sys.argv:
           if u == sys.argv[0]:
                continue
           os.system("useradd -m -p "+encPassword+" -e "+expire+" " + u)

Of course we have to make sure that we do not use element 0 which is the script name, hence the if statement.