Last updated: Apr 13, 2024
Reading time·3 min
The error "python.exe: can't find '__main__' module in Path" occurs for multiple reasons:
.py
.if __name__ == "__main__":
conditional correctly.The first two things you should check are that:
You've saved your file. In most code editors, you can press Ctrl
+ S
or
Cmd
+ S
(on macOS).
You've given your Python script a .py
extension, e.g. example.py
or
app.py
.
Try to rerun your file after making sure that it has a .py
extension and has
been saved.
if __name__ == "__main__":
conditional correctlyAnother thing you should check is that you've added the
if __name__ == "__main__":
conditional correctly.
def do_work(): print('bobbyhadz.com') if __name__ == '__main__': # Call functions or run logic here 👇️ do_work()
The if
statement that checks if __name__
is equal to '__main__'
ensures
that the if
block only runs if the file is run directly with
python script_name.py
.
main.py
, the code in the if
block would only run if your script is run with python main.py
.The __name__
global variable is only set to '__main__'
when the file is run
directly with python your_script.py
and not when it's imported into a
different file.
If you use the PyCharm IDE, make sure your "Script path" is set correctly.
Run
in the top menu and select "Edit Configurations".The Script Path should be the complete path to your Python script, including the filename and extension.
You can click on the folder icon next to the Script Path option to select your Script Path by navigating directories instead of manually typing it in.
Make sure to click on Apply and OK once you've selected the correct Script Path.
If that doesn't work, press Alt
+ Shift
+ F10
.
Select your module's name and hit Enter
.
Once you've selected your module's name you can press Shift
+ F10
on
subsequent runs.
You can learn more about the related topics by checking out the following tutorials: