Run a Python file with relative import in PyCharm

Have you ever tried running a Python file with relative import on PyCharm and it didn't work?

TL;DR

Set the Sources Root properly and add External Tools with the above settings.

The problem you want to solve

For example, create the following file in your own package called my_pkg.

my_pkg/foo.py


x = 42

my_pkg/bar.py


from .foo import x

if __name__ == '__main__':
    print(x)

If you open my_pkg / bar.py in PyCharm and simply run it, you will get the following exception.

/usr/bin/python3 /tmp/my_pkg/bar.py
Traceback (most recent call last):
  File "/tmp/my_pkg/bar.py", line 1, in <module>
    from .foo import x
ModuleNotFoundError: No module named '__main__.foo'; '__main__' is not a package

Process finished with exit code 1

Cause

The reason is explained in detail in the article here. In conclusion, it works fine if you run it with the -m option and the fully qualified name of the module (my_pkg.bar).

# ERROR!!
/usr/bin/python3 /tmp/my_pkg/bar.py

# OK
cd /tmp
/usr/bin/python3 -m my_pkg.bar

In other words, you can somehow get PyCharm to run in the -m option format.

Solution 1. Be honest with Edit Configuration settings

You can run it in the -m option format by setting it as shown in the image below. However, this method has the very serious problem of ** having to set this every time you want to run **.

edit_configurations.png

edit_configurations2.png

Solution 2. Use External Tools

PyCharm has a function to handle external executable files, so take advantage of it. It's a bit annoying, but the advantage is that you only need to set it once and it can be used in all projects.

Creating a new External Tools

Go to File → Settings → Tools → External Tools on the menu bar to add a new External Tools.

external_tools.png

external_tools2.png

Please set the Tool settings part as follows.

Sources Root settings

All you have to do is right-click on the parent directory of my_pkg and register it as Sources Root.

external_tools3.png

Run

With bar.py open, click Tool-> External Tools-> python -m on the menu bar. If you can do it properly, you are successful. If you use it frequently, it is convenient to assign a shortcut key.

Recommended Posts

Run a Python file with relative import in PyCharm
Read a file in Python with a relative path from the program
Run python with PyCharm (Windows)
A memorandum to run a python script in a bat file
Working with LibreOffice in Python: import
Create a binary file in Python
Run a simple algorithm in Python
How to import a file anywhere you like in Python
[Note] Import of a file in the parent directory in Python
Spiral book in Python! Python with a spiral book! (Chapter 14 ~)
Creating a simple PowerPoint file with Python
Run the Python interpreter in a script
[GPS] Create a kml file in Python
Run a Python web application with Docker
I made a configuration file with Python
Create a shortcut to run a Python file in VScode on your terminal
A memo organized by renaming the file names in the folder with python
Run a Python file inside a Docker container on a remote Raspbian via PyCharm
Read a Python # .txt file for a super beginner in Python with a working .py
How to read a CSV file with Python 2/3
[Python] Get the files in a folder with Python
Read a file containing garbled lines in Python
Building a Python environment with WLS2 + Anaconda + PyCharm
How to create a JSON file in Python
Read table data in PDF file with Python
Python> Run with run-time arguments> Use import argparse
Work in a virtual environment with Python virtualenv.
Create a new page in confluence with Python
Run a Python file from html using Django
Create a Photoshop format file (.psd) with python
Create a MIDI file in Python using pretty_midi
Read line by line from a file with Python
I want to write to a file with Python
Open a file dialog with a python GUI (tkinter.filedialog)
File operations in Python
Run Python with VBA
File processing in Python
Run prepDE.py with python3
Run Blender with python
File operations in Python
Import tsv with Python
Run iperf with python
Put Docker in Windows Home and run a simple web server with Python
How to drop Google Docs in one folder in a .txt file with python
Parse a JSON string written to a file in Python
How to convert / restore a string with [] in python
Specify upper directory / subdirectory with relative import of Python
Make a simple Slackbot with interactive button in python
How to run tests in bulk with Python unittest
Try embedding Python in a C ++ program with pybind11
Create a plugin to run Python Doctest in Vim (1)
I want to randomly sample a file in Python
I want to work with a robot in python.
[Python] Create a Tkinter program distribution file with cx_Freeze
Create a fake Minecraft server in Python with Quarry
I want to run a quantum computer with Python
Create a 2d CAD file ".dxf" with python [ezdxf]
Run the output code with tkinter, saying "A, pretending to be B" in python
Create an exe file that works in a Windows environment without Python with PyInstaller
I got stuck when trying to specify a relative path with relative_to () in python
Python2 / numpy> Replace only a specific column in a file with column data from another file> numpy.c_