0

I have a code which I'd like people to be able to use as a stand alone python program, or to import as a module for their own codes. Is there a way to package a module which can also include a program that can be run from the command line?

I.e. from the command-line:

> ZHermesCode

or within ipython or a python script:

import ZHermesCode
1
  • you want to run your python script from command line or some inbuilt module??? Commented Nov 19, 2014 at 3:59

2 Answers 2

2

Look up Setuptools automatic script creation. For example, python-scss uses this technique to make scss an executable shell command.

In setup.py:

setup(
    # ...
    entry_points={
        'console_scripts': [
            'scss = scss.tool:main',
        ]
    },
)

Then defining a function main in scss/tool.py. It also uses the technique mentioned by Loocid to make the tool.py file itself directly executable (as opposed to the wrapper script that is publicly installed by setuptools according to the recipe above):

if __name__ == '__main__':
    main()
Sign up to request clarification or add additional context in comments.

Comments

1

If you use:

if name == '__main__':

The code held in that 'if' statement will only be ran if someone runs your program from the command line.

If someone was to import your module instead, the code will not run.

Eg

def test(st):
    return(st)

if name == "__main__":
    print(test("hello"))

If you run this program from the command line, it will print "hello". However, someone could also import this module and have access to the "test" function to use in their own programs.

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.