Have you ever tried running a Python file with relative import on PyCharm and it didn't work?
TL;DR
$ModuleSdkPath$
-c "import os,runpy;runpy.run_module('.'.join(r'$FilePathRelativeToSourcepath$'.replace(os.sep,'.').split('.')[:-1]),{},__name__,1)"
$Sourcepath$
Set the Sources Root properly and add External Tools with the above settings.
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
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.
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 **.
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.
Go to File → Settings → Tools → External Tools on the menu bar to add a new External Tools.
Please set the Tool settings part as follows.
$ModuleSdkPath$
-c "import os,runpy;runpy.run_module('.'.join(r'$FilePathRelativeToSourcepath$'.replace(os.sep,'.').split('.')[:-1]),{},__name__,1)"
$Sourcepath$
All you have to do is right-click on the parent directory of my_pkg
and register it as Sources Root.
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