Chapter 7: Modules

Introduction

There are various methods of writing modules, but the simplest way is to create a file with a .py extension that contains functions and variables.

You can write modules in the C programming language.

using_sys.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Filename: using_sys.py

import sys

print('The command line argument are:')

for i in sys.argv:
    print(i)

print('\nThe PythonPATH is', sys.path)

using_sys.py の実行結果は:

[wtopia py.byte]$ python3 using_sys.py P1 P2 P3 P4
The command line argument are:
using_sys.py
P1
P2
P3
P4

The PythonPATH is ['/Users/wtopia/src_python/sphinx/py.byte', '/usr/local/lib/python31.zip', '/usr/local/lib/python3.1', '/usr/local/lib/python3.1/plat-darwin', '/usr/local/lib/python3.1/lib-dynload', '/usr/local/lib/python3.1/site-packages']

Run:

>>> import os
>>> print(os.getcwd())
/Users/wtopia/src_python/sphinx/py.byte

to find out the current directory of your program.

Byte-compiled .pyc files

.pyc file is useful when you import the module the next time from a different program - it will be much faster since a portion of the processing required in importing a module is already done.

Also, these byte-compiled files are platform-independent.

The from ... import ... statement

If you want to directly import the argv variable into your program (to avoid typing the sys. everything for it), the you can use the:

from sys import argv

If you want to import all the names used in the sys module, then you can use the:

from sys import *

In general, you should avoid using this statement and use the import statement insted since your program will avoid name clashes and will be more readable.

using_sys2.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Filename: using_sys2.py

from sys import *

print('The command line argument are:')

for i in argv:
    print(i)

print('\nThe PythonPATH is', path)

using_sys2.py の実行結果は:

[wtopia py.byte]$ python3 using_sys2.py P1 P2 P3 P4
The command line argument are:
using_sys2.py
P1
P2
P3
P4

The PythonPATH is ['/Users/wtopia/src_python/sphinx/py.byte', '/usr/local/lib/python31.zip', '/usr/local/lib/python3.1', '/usr/local/lib/python3.1/plat-darwin', '/usr/local/lib/python3.1/lib-dynload', '/usr/local/lib/python3.1/site-packages']

A module’s __name__

Making Your Own Modules

The dir function

Packages