5

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?

2
  • Please include a minimal example of a file that runs one way, but not the other. Commented Jul 25, 2017 at 0:28
  • 1
    Possible duplicate of Execution of Python code with -m option or not Commented Jul 26, 2019 at 3:18

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.