Running a package as a script: executing __main__.py without importing __init__.py
<p>My package directory is as follow:</p>

<pre><code>foo/
    __init__.py
    __main__.py
setup.py
</code></pre>

<p>If that matters, I installed it using setuptools.</p>

<p>Now, if I have a Python code with the line <code>import foo</code>, then <code>__init__.py</code> is executed and <code>__main__.py</code> is not executed. This is fine.</p>

<p>But if I run the command <code>python -m foo</code>, both <code>__init__.py</code> and <code>__main__.py</code> are executed. I would like <code>__main__.py</code> to be executed without <code>__init__.py</code>.</p>

<p><strong>How can I achieve that?</strong></p>

<p>I have the desired behavior if I run <code>python foo</code> when <code>foo</code> is in my working directory. However, this does not work anymore when I run the command from some other directory (I have the error <code>No such file or directory</code>, as expected).</p>

<hr>

<p>The motivation behind that is that <code>foo</code> is a library that relies on some shared C library (call it <code>c_foo</code>). You cannot import <code>foo</code> if <code>c_foo</code> doesn't exist on your system (it throws an exception). I do not want to install automatically <code>c_foo</code> with setup.py since it may be shared or the user may want to have a custom installation. However, I want to embed an installation script in <code>foo</code> to help the user to install <code>c_foo</code> if needed. So I would like <code>python -m foo</code> to be the entry point of the installation script.</p>

<p>You can't. <code>__init__</code> is the <em>core</em> of the package and will <strong>always</strong> be imported for anything from the package.</p>

<p>You'll have to move the code from <code>__main__.py</code> to live outside the package, or move the code you don't want executed from <code>__init__.py</code> to another module.</p>

python package