Dims
Dims

Reputation: 51239

How to run module from command line?

Suppose there is a module somewhere, which I can import with

from sound.effects import echo

How can I run echo directly from command line?

Command

python sound/effects/echo.py

does not work since the relative path is generally incorrect

Upvotes: 3

Views: 4391

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124768

If the module has top-level code executing on import, you can use the -m switch to run it from the command line (using Python attribute notation):

python -m sound.effect.echo

The module is then executed as a script, so a if __name__ == '__main__': guard will pass. See for example the timeit module, which executes the timeit.main() function when run from the command line like this.

Upvotes: 9

Related Questions