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 possible be asked to run the script 100 times!

Another good way to let user enter input is directly via command-line arguments when you are executing your script, i.e. python my_script.py. For example, you might want to let users pre-enter 5 guesses for your 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])  # get the 1st guess (35 for the above example)
    print(sys.argv[2])  # get the 2nd guess (21)
    print(sys.argv[3])  # get the 3rd guess (10)
    print(sys.argv[4])  # get the 4th guess (28)
    print(sys.argv[5])  # get 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!