Suppose a python module file mdl.py contains the required code at the end of the file mdl.py so that it can be used as a script as well as an importable module. Now can we run script mdl.py by the following command at python shell?
>>>import mdl
If the module is configured correctly, then the following call should work:
python -m mdl
module-name. When invoking Python, you may specify any of these options: python [-bBdEhiIOqsSuvVWx?] [-c command | -m module-name | script | - ] [args]Yes, you can run script by importing it.
Consider you have file mdl.py:
print("foo")
if __name__ == "__main__":
print("bar")
If you call import mdl from python shell it will print line "foo". If you start this file with python mdl.py it will print lines "foo" and "bar".
It's not a good practice, btw.
You can do that but it is not considered good style. Importing a module should ideally not have side effects except making the functions and objects defined in the module available.
The canonical way to structure your module can be seen in the example below.
if __name__ == '__main__' block.If you run the module as a script, the __name__ of the module is set to '__main__'. If you import the module, the name is set to the name of the module.
So if you give the command python3 pdfinfo.py foo.pdf it will extract information from the file foo.pdf.
If you do import pdfinfo in Python, it will make pdfinfo.pdfinfo available to your program.
Example:
# file: pdfinfo.py
# vim:fileencoding=utf-8:fdm=marker:ft=python
"""Module to retrieve information from a PDF file."""
import sys
import logging
def pdfinfo(path):
lookups = (b'/Author', b'/Creator', b'/Producer', b'/CreationDate', b'/ModDate')
logging.debug(f'reading {path}')
with open(path, 'rb') as f:
data = f.read()
# Find the trailer, and the Info reference in the trailer
istart = data.find(b'\ntrailer') + 8
istart = data.find(b'/Info', istart) + 6
iend = data.find(b'R', istart) - 1
# Extract the Info object number and generation
objid = data[istart:iend].strip()
logging.debug('Info object is ' + objid.decode('ascii'))
ostart = data.find(objid + b' obj')
ostart = data.find(b'<<', ostart) + 3
oend = data.find(b'>>', ostart)
# For now.
# return data[ostart:oend]
info = data[ostart:oend]
locations = [
(data.find(item), item.decode('ascii')) for item in lookups if item in info
]
locations.sort(key=lambda i: i[0])
logging.debug('found ' + ' '.join(t[1] for t in locations))
return locations
# Run a test.
def _main(argv):
"""
Entry point for pdfinfo.py.
Arguments:
argv: command line arguments; names of PDF files to scan.
"""
logging.basicConfig(level='DEBUG', format='%% %(levelname)s: %(message)s')
for fn in argv:
logging.info(pdfinfo(fn))
print('-----------------------------------------')
sys.stdout.flush()
if __name__ == '__main__':
_main(sys.argv[1:])