Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

The sys.argv in Depth

00:00 In the last lesson, I showed you how to use the sys.argv list to get the arguments passed in to a Python program from the command line. In this lesson, I’ll go a little bit more in-depth into what the sys.argv list is and how it’s structured.

00:17 The simplest thing about the sys.argv paradigm that Python sets up is that this sys.argv object is just a list, and it’s a simple list of strings just like any other list of strings. However, this can also cause some issues because it’s not a very sophisticated way to represent the arguments. For example, those strings need to represent arguments of any type, like integers and file paths and stuff. And they do an admirable job of that, but they also don’t give you any built-in error handling or anything like that, so you’re going to have to do a little bit of extra work to make a really sophisticated, complex command line interface. But the sys.argv list is really quite simple.

01:00 Say that I have a file called f.py that I want to call from the command line—or I want to execute from the command line, I should say—with four arguments.

01:09 sys.argv would be as shown here on the right. The filename always occupies the zeroth index of sys.argv, and then the arguments are then put into the list in succession.

01:21 So, this part is really simple. They’re just passed in—in the same order that they were passed on the command line, they will exist in the sys.argv. But of course, you might run into issues if, for example, an unsupported number of arguments is passed in or arguments of types that are unexpected are passed in. So say, for example, you want arg3 to be a file so that you can open that file and write to it.

01:44 But if arg3 doesn’t actually represent a file, then you’ll run into an error—a FileNotFoundError. And so you’ll have to put in some error handling on your own, which is something that I’ll cover in the next lesson: how to handle the fact that this representation is so simple—it’s just a list of strings—but how to handle the fact that that doesn’t really quite give you super-easy ways to enforce the correct formatting of a command line interface. So in the next lesson, I’ll head over into a code editor and show you several examples of the different problems you might run into as you work with integrating command line arguments into your Python code, and how to resolve—or at least mitigate—those problems.

Become a Member to join the conversation.