How to Call Python Files?

Learn about the different ways of calling Python files.

There are two ways to call Python files:

  1. We can call the file directly (Python [filename]), which is what we’ve been doing.

  2. We can call the file using an external library.

We haven’t covered calling the file using an external library yet. If we wanted to use the function count_words in another file, we would do this:

from word_count import count_words

This will take the function count_words and make it available in the new file. We can also do the following:

from word_count import *

This will import all functions and variables, but generally, this approach isn’t recommended. It would be best if we only imported what we needed. Furthermore, we’ll sometimes have a code we only want to run if the file is being called directly (without an import). In that case, we can put it under this line:

if __name__ == "__main__":

This means “only run this code if we are running this file from the command line." If we import this file in another, all of this code will be ignored.

Using this syntax ensures that our function only runs when someone calls our program directly and does not import it as a module.

Note: __name__ is an internal variable set to __main__ by the Python interpreter when running the program standalone.

In our examples, we’ve been calling the files directly. However, we thought we’d show the following syntax as well. It is optional, but good practice for whenever we want to turn our code into a library. Even though you might not need to now, it’s good practice to include the command as it’s only one line.

 if len(sys.argv) < 2:
        print("Usage: python word_count.py <file>")
        exit(1)

The sys library contains several system calls, one of which is the sys.argv command, which returns the command line arguments.

We’re already familiar with len(). Let’s check if the number of command-line arguments is less than two.

The first argument is always the name of the file.

WordCount> python ./word_count.py

If so, print a message and exit. This is what happens when we pass one argument to the function.

Output: Usage: python word_count.py <file>

The next line:

filename = sys.argv[1]

As we said, the first element of sys.argv (or argv[0]) will be the name of the file itself (word_count.py in our case).

The second will be the file the user entered. We’ll read that:

f = open(filename, "r")
data = f.read()
f.close()

We’ll read the following data from the file:

num_words = count_words(data)
num_lines = count_lines(data)
print("The number of words: ", num_words)
print("The number of lines: ", num_lines)

And now we’ll call our functions to count the number of words and lines. Then we’ll print the results. Voila! We’ve created a simple word counter.

Get hands-on with 1200+ tech skills courses.