This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 6: JSON files

sys.argv

face Josiah Wang

You might have hardcoded the filename of the JSON in your code earlier ("dataset.json" and "visualisation.json").

Sometimes you might not know in advance what the filenames are. In such cases, it might be more convenient to let the user enter it when executing your script.

You can use input(), but this can sometimes be cumbersome and hard to automate. Imagine you want to test 100 different input values - you cannot possibly be asked to run the script 100 times and manually enter each value each time!

Another good way to let users enter input is directly via command-line arguments when the user is executing your script, i.e. python my_script.py. For example, you might want to let users pre-enter 5 guesses for your good old guessing game without having to prompt for them individually.

$ python guessing_game.py 35 21 10 28 42

To do this, you use the sys.argv variable (a list) provided by Python. For the example above, sys.argv[0] will contain the first argument, that is the name of your script (guessing_game.py). sys.argv[1] will contain the string "35", sys.arv[2] the string "21" etc.

import sys

if __name__ == "__main__":
    if len(sys.argv) < 6:
        print("Usage: python guessing_game.py 1st_guess 2nd_guess 3rd_guess 4th_guess 5th_guess") 
        exit()

    print(sys.argv[0])  # guessing_game.py
    print(sys.argv[1])  # print the 1st guess (35 for the above example)
    print(sys.argv[2])  # print the 2nd guess (21)
    print(sys.argv[3])  # print the 3rd guess (10)
    print(sys.argv[4])  # print the 4th guess (28)
    print(sys.argv[5])  # print the 5th guess (42)

Task: Reading JSON files via command line argument

Here is a quick task: modify your code from the previous exercise, so that a user can pass the input JSON filename and output JSON filename via command line.

$ python convert_json.py dataset.json visualise.json

You can change the name of the output JSON file to something else just to test that it works!