Bootstrap FreeKB - Python (Scripting) - Creating your own modules
Python (Scripting) - Creating your own modules

Updated:   |  Python (Scripting) articles

There are several built in modules that are part of the Python Standard Library included with your Python installation, such as os (Operating System) and re (Regular Expression) and sys (System). For example, here is how you would import the sys module and then use the sys module.

#!/usr/bin/python
import sys
print(sys.argv[0])

 

Which should print the following (the name of your Python script).

~]$ python testing.py
testing.py

 

However, there will ineviatabley be situations where you'll want to create your own module. A module is simply a Python file with the .py extension that does something. For example, let's say you have a file named greeting.py that contains the following.

#!/usr/bin/python
def hello():
  return "Hello World"

 

If you create some other Python file such as main.py in the same directory as greeting.py, here is how you can use the hello function from greeting.py in main.py.

#!/usr/bin/python
import greeting
print(greeting.hello())

 

Or, you could use from greeting import hello like this.

#!/usr/bin/python
from greeting import hello
print(hello())

 

Running main.py should print Hello World.

~]$ python main.py 
Hello World

 

Python modules are typically located somewhere below sys.path. Here is how you can print the system paths.

#!/usr/bin/python
import sys

print("System Paths:")
directories = sys.path
for directory in directories:
  print(directory)

 

Which should return something like this.

/home/john.doe
/usr/lib64/python27.zip
/usr/lib64/python2.7
/usr/lib64/python2.7/plat-linux2
/usr/lib64/python2.7/lib-tk
/usr/lib64/python2.7/lib-old
/usr/lib64/python2.7/lib-dynload
/usr/lib64/python2.7/site-packages
/usr/lib/python2.7/site-packages

 

Let's say main.py and greeting.py are located in different directories and the greeting.py module is not located in one of the sys.path directories. Running main.py should raise something like this.

~]$ python main.py 
Traceback (most recent call last):
  File "/tmp/main.py", line 3, in <module>
    from greeting import hello
ImportError: No module named greeting

 

The following could be included in main.py to append the directory that contains the greeting.py module. However, this is more of a temporary solution rather than a permanent solution.

sys.path.append("/tmp")

 

One permanent solution would be to move the greeting.py module you created into one of the sys.path directories, such as /usr/lib64/python2.7/site-packages.




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter b817d6 in the box below so that we can be sure you are a human.