Running from __main__ in PyCharm

This applies to PyCharm 2016.3.2.

Sometimes it’s useful to run a module, that is part of a bigger project, directly from PyCharm. To prevent that code from running with the module is being called from elsewhere, you can use something like this:

def my_module(x, y):
    return 'hello world'

if __name__ == '__main__':
    results = my_module(x, 7)

Sometimes when you do that, you will get import errors. Not a problem, just make sure the dir that contains the package that contains the module is on the sys path. To check that, put this at the top of the module:

import sys
for p in sys.path:

Here’s where PyCharm gets a little tricky. You would think you could just go into the Run/Debug Configurations and set the Working directory. Unfortunately that does not work. Instead you need to add an Environment variable PYTHONPATH. Like this:




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s