How to write a Python file so that it can be either a module or a script with command line parameters and channel capabilities?

I am considering how a Python file can be an imported module, as well as a script that is able to accept command line parameters and arguments, as well as channel data. How to do it?

My attempt seems to work, but I want to know how my approach is how it should be done (if necessary). Could there be difficulties (for example, when importing) that I did not consider?

#!/usr/bin/env python

"""
usage:
    program [options]

options:
    --version        display version and exit
    --datamode       engage data mode
    --data=FILENAME  input data file [default: data.txt]
"""

import docopt
import sys

def main(options):

    print("main")

    datamode            = options["--datamode"]
    filename_input_data = options["--data"]

    if datamode:
        print("engage data mode")
        process_data(filename_input_data)

    if not sys.stdin.isatty():
        print("accepting pipe data")
        input_stream = sys.stdin
        input_stream_list = [line for line in input_stream]
        print("input stream: {data}".format(data = input_stream_list))

def process_data(filename):

    print("process data of file {filename}".format(filename = filename))

if __name__ == "__main__":
    options = docopt.docopt(__doc__)
    if options["--version"]:
        print(version)
        exit()
    main(options)
+4
source share
1 answer

What is it, you are good .

[1], if __name__ == '__main__',

docs ( ):

__name__ '__main__' , script . , , __name__, , script python -m

, python 2 docs

, " script" script:

, , ; . , /, .


?

:

  • ( , ). if __name__ == '__main__' .
  • C, , ifdef . python, , .

main, C Java, - ? .


! , - . . , , .


-m. , ?! , .


[1] , , , . -

+4

All Articles