4

What's the difference between running python file as a module executed as a script vs just running the python file? In particular, I'm wondering what the difference is between running

python -m filename vs python filename.py

I'm reading the documentation here: https://docs.python.org/3.6/using/cmdline.html but it's not entirely clear to me.

In particular, I notice that when I'm running a file I wrote that imports other modules I've written, it works when I run python -m filename but when I run python filename.py it says it can't find the module I've written. Why is this? Is this something to do with the path?

Vincent
  • 7,808
  • 13
  • 49
  • 63
  • Please include a minimal example of a file that runs one way, but not the other. – DYZ Jul 25 '17 at 00:28
  • 1
    Possible duplicate of [Execution of Python code with -m option or not](https://stackoverflow.com/questions/22241420/execution-of-python-code-with-m-option-or-not) – AXO Jul 26 '19 at 03:18

1 Answers1

3

I am not a python guy but I read something in the link you have provided that may provide some explanation.

If this option is given, the first element of sys.argv will be the full path to the module file (while the module file is being located, the first element will be set to "-m"). As with the -c option, the current directory will be added to the start of sys.path.

I guess what that means is that the directory you are running python -m filename is added to the system path. The sys.path (or system path) is basically a list of paths (folders) that python will try search for the file you are trying to import. I am assuming the files you are looking for in your import is in the same folder you run python -m filename. Running python without the -m does not modify the sys.path list.

You can read more on this here https://docs.python.org/3.6/library/sys.html#sys.path

Hope this is what you want.

alaboudi
  • 3,187
  • 4
  • 29
  • 47