1

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)

Régis B.
  • 10,092
  • 6
  • 54
  • 90

3 Answers3

3

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!
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

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?

Community
  • 1
  • 1
n611x007
  • 8,952
  • 8
  • 59
  • 102
0

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!
ostrokach
  • 17,993
  • 11
  • 78
  • 90