Python language basics 24: adding a command line argument
June 27, 2015 1 Comment
Introduction
In the previous post we investigated the role of the global __name__ variable in Python and how it could be used to execute a function from the command line. The __name__ variable evaluates to “__main__” in case the Python file is not merely imported into another one but instead is the main file being called from the command line.
In this post we’ll discuss how to execute a Python file and pass in an argument from the command line.
Arguments into the entry point
Let’s say that we want to send a greeting to the player in the beginning of the game, like “Welcome to the game, [your name]”. That should be possible without explicitly asking for the player’s name in the beginning of the game.
It is possible to pass in an arbitrary number of arguments into a Python module from the command line. The arguments will be stored in a string array. The array can be accessed through the “argv” parameter of the “sys” module. “Sys” enables us to access some system-specific parameters and functions as described in detail here.
Hence the following…
sys.argv
…returns an array of strings containing all the arguments that were passed into the module from the command line. Just like we saw with the name “__main__” the “argv” parameter will immediately look familiar to those coming from the world of C-like languages such as Java or C#. The standard form of the “main” function in those languages includes a string array parameter like here:
public static void main(string[] args) { }
Let’s test this. We’ll rename the start_game function to main in our number guessing game code, pass in sys.argv as the method argument from the final if-block and print the contents of sys.args within the main method:
def main(args): print(args) lower_limit_input = get_integer_input('Lower limit: ') upper_limit_input = get_integer_input('Upper limit: ') guess_counter = play_game(lower_limit_input, upper_limit_input) finish_game(guess_counter) if __name__ == '__main__': main(sys.argv)
You’ll need to add the following import statement at the top of the source file:
import sys
…in order to import the system-related module.
Run the game from the command line as we saw in this post. The main method will be called as __name__ evaluates to __main__ hence the contents of sys.args will be printed:
So you’ll see that the source file name will be inserted as the first element into the string array of sys.argv by default.
You can easily add your own arguments. Append them to the command as a space-delimited list like here:
If a single argument consists of multiple words then you can enclose them in quotation marks as follows:
So if we pass in a name then it will be the second element in the arguments list as the first, i.e. position 0 will be occupied by the source file name. Here’s the form of NumberGuessing.py which greets the name of the player from the main function:
import sys from random import randint def get_integer_input(prompt_text): user_input = input(prompt_text) return int(user_input) def evaluate_guess(guess, random_number): if guess > random_number: print('Too large') else: print('Too small') def finish_game(guess_counter): print('Congratulations. It took you ' + str(guess_counter) + ' guesses to guess the correct number.') def play_game(lower_limit, upper_limit): random_number = randint(lower_limit, upper_limit) guess = get_integer_input('Your first guess: ') guess_counter = 1 while random_number != guess: evaluate_guess(guess, random_number) guess_counter += 1 guess = get_integer_input('Your next guess: ') return guess_counter def main(args): gamer = args[1] print("Welcome to the game", gamer, "!") lower_limit_input = get_integer_input('Lower limit: ') upper_limit_input = get_integer_input('Upper limit: ') guess_counter = play_game(lower_limit_input, upper_limit_input) finish_game(guess_counter) if __name__ == '__main__': main(sys.argv)
Call it with an extra argument such as…
python NumberGuessing.py “Elvis Presley”
…and you’ll see the initial greeting in the command prompt.
In the next post we’ll look into code documentation through comments.
Read all Python-related posts on this blog here.
Hi, Adras!
Thanks a lot for your tutorial 🙂