0

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
0

3 Answers 3

1

If the module is configured correctly, then the following call should work:

python -m mdl
Sign up to request clarification or add additional context in comments.

2 Comments

what is the -m for?
To specify module-name. When invoking Python, you may specify any of these options: python [-bBdEhiIOqsSuvVWx?] [-c command | -m module-name | script | - ] [args]
1

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.

Comments

1

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.

  • Start with a comment containing information about the file. This usually includes e.g. a copyright notice.
  • Add a module docstring to describe what the module does.
  • Import whatever modules you need.
  • Define your classes and functions. (Functions whose name start with an underscore are considered "private".)
  • To be able to run the module as a script, you add a 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:])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.