Régis B.
Régis B.

Reputation: 10618

Running function in __main__ .py from command line

I've got the following __main__.py file:

def all():
    print "hello world!"

if __name__ == "__main__":
    print "bar"

How can I run function all from the command line? The following don't seem to work:

python -c "import __main__; __main__.all()"
python .

I am not allowed to modify the __main__.py file. (This is for a FLOSS project that I'm trying to contribute to)

Upvotes: 1

Views: 1953

Answers (3)

ostrokach
ostrokach

Reputation: 19982

If you are using setup.py to install this package, you can add a command-line entry point for the all function:

from setuptools import setup

setup(
    name='mypackage',
    version='1.0',
    packages=['mypackage'],
    entry_points={
        'console_scripts': [
            'mypackage_all = mypackage.__main__:all',
        ],
    },
)

After running python setup.py develop or python setup.py install, you will be able to call the all function using mypackage_all:

$ mypackage_all
hello world!

Upvotes: 0

n611x007
n611x007

Reputation: 9272

You probably don't want to do this but if __main__.py is in your working directory:

python -c "import imp; trick = imp.load_source('__main__', './__main__.py'); trick.all()"

If your file sits in a directory like foo/__main__.py then you can do

python -c "import imp; trick = imp.load_source('foo.__main__', 'foo/__main__.py'); trick.all()"

See also What is __main__.py? and How to import a module given the full path?

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124060

The __main__ module is always part of a package. Include the package name when importing:

python -c 'from package.__main__ import all; all()'

Demo:

$ mkdir testpackage
$ touch testpackage/__init__.py
$ cat << EOF > testpackage/__main__.py
> def all():
>     print "Hello world!"
> if __name__ == '__main__':
>     all()
> EOF
$ python testpackage
Hello world!
$ python -c 'from testpackage.__main__ import all; all()'
Hello world!

Upvotes: 3

Related Questions