Recently I switched computers and re-downloaded my python and pycharm, I tried activating my saved projects on the new computer, but I ran into problem, pycharm doesn't recognize the parent folder of some of the files, and mistakes it for a module.
The folder is called: "Enrichment_extra_stuff", and when I try to import file in that folder, from another file in that folder, it seems like pycharm recognize it, because it shows me all of the files inside it, but when I run the code, I get the error ModuleNotFoundError: No module named 'Enrichment_extra_stuff'.
Also weirdly, when I try doing explict import and just write import fr to import the file fr, then pycharm shows an error but when I run it, it works like it should.
I tried digging a bit on pycharm, but got confused and didn't found anything, my python interpreter version is 3.8 and I program on windows if that helps.
A folder (or better a directory) is not seen as a module, unless you put __init__.py file in it. This could be empty, or it should be the module content. This is Python: a module is either a file, or a directory with __init__.py
The second part is only for Pycharm: PyCharm is created to handle large projects, and often your program is not in the base (root) directory of your project, but in one (or more) subdirectories (e.g. src). So you should explicitly tell PyCharm which are the root directories. So, go to the project structure panel (the panel with the files, usually on left side), go to your "root" directory, and set with right mouse click on your base source directory: on the pop-up menu select Mark directory as, and then select Source Root.
Related
I'm trying to run some code on VSCode, as I'm shifting over from PyCharm and Vim to utilise VSCode as a general purpose editor for a variety of programming languages.
I'm currently trying to make some code work, which should have been quite straight forward given it is a project in my PyCharm IDE and I have been able to run it there.
When I open up my VScode workspace, and try and run the code, it cannot find a directory that obviouslly exists:
So I'm getting this error:
Exception has occurred: FileNotFoundError
data/connectivity/weights.txt not found.
And, my code is also pretty straight forward, its something like this:
SC = np.loadtxt(join("data/connectivity", "weights.txt"))
numpy is loaded in as np. and os.path.join is loaded in as join.
The directory data/ is in the same parent directory as the code/script I'm running.
I have no idea why it isn't recognising the path, or the folder.
**NOTE: **
To add, when I run my code in jupyter notebook in VSCode, it runs smoothly and recognises the path.
The jupyter notebook is also in the same parent directory as the data/ directory. So there is no visible difference between the .py and .ipynb files regarding code and relative position to the data/ directory.
Any help would be much appreciated. There is probably a simple solution that I'm failing to catch onto at the moment.
Thanks,
Boki
I've tried changing the directory to an absolute path on my Mac, which didn't work.
I also tried--though probably not so usefully--adding __init__py files to each of the subdirectories, but as they are not modules, this was sort of pointless, I was just trying to be exhaustive.
As I mention above, code works perfectly when I run the same code as a .ipynb, or when I run it in my old IDE: PyCharm
This is because the current directory of the terminal is different when vscode and pycharm run files.
By default, vscode executes files in the workspace, and pycharm executes files in the folder where the files are run.
You can search Terminal: Execute In File Dir in settings and check it.
This will be consistent with pycharm.
Of course, the default setting of vscode is also beneficial. When encountering multi-level directories, it is more convenient to import files.
I am new in Python and pycharm ide.
I have created one of my own module and importing it in another python file.
Both of my python files are in same direcotary and parent directory has been made Sources Root directory.
Now my program is working fine but pycharm ide is showing error in import statement and on hover prompting no such module.
I am not sure if i am doing something wrong please let me know what is the proper way to import a module.
here is my project structure -
Main.py is importing Greeting.py and getting error.test is a root directory.
For my case, I had my problem was not resolved by invalidating the cache,
My problem was with the directories (packages) and the root directory.
Here was my structure.
MyApp:
|
|----my_first_app
|--------my_first_app_files
|--------my_first_app_directories
|----my_second_app
|--------my_second_app_files
|--------my_second_app_directories
So what I did on my editor was I right clicked app:>mark directory as:>sources root
Referrence
Link
invalidate cache and restart resolved the problem.
jetbrains.com/help/pycharm/cleaning-system-cache.html
When I run my Main.py script, PyCharm keeps telling me Cannot start process, the working directory /home/myname/PyCharmProjects/MyProjectName/mypackage does not exist.
This error occurred after creating a package (mypackage) for test purposes, moving files to it (including Main.py), and moving the files back to the root folder afterwards.
The package mypackage was empty after that, but PyCharm still thought that Main.py is located in that package. I could still run the program until I deleted the empty package, but path errors occurred. After deleting the package, I was unable to start it.
I can still run the other files that used to be in mypackage and are now in my root directory again.
I can still create and run new files in my root directory.
It happens because when you create a file it automatically assigns the working directory to it's configuration, which of course is the one where you created it.
You can change that by going into Run -> Edit Configurations. Click on the folder icon in Script path: and correct the path to the file. Click OK to save and you should be able to Run the file again.
After testing for a bit, I've found a solution (but not an answer to why this error occurs in PyCharm):
Delete the file and create it again. (Or rename or move it and create a new file with its old name, both should work.)
Set the working directory correctly
1. File-> Settings
2. Build, Execution, Deployment -> Console -> Python Console
3. Working directory: [The path to the directory where the file you're currently working on resides.]
I had the same problem, mine is probably related to the explaination gave by the others, it comes from the dir .idea, files *.xml contain the variable $DIR_PROJECT$.
Therefore, as the attribution of a new path didn't work, I just deleted my .idea, that is automatically loaded each time I open my project's directory.
It automatically regenerated the .idea, asked for the script path... And it worked perfectly
CAREFUL => You will automatically lose your project settings, you are deleting the "settings file"
I was getting this same error, and the path in "edit configurations" was correct.
However, this is what eventually got my code working again.
1) I commented out all of the code in my file ("ctrl" + "a" + "ctrl" + "/")
2) I commented something I knew would compile in the file. (my list of imports)
3) I ran the python file.
This time, it actually completely compiled and after that I was able to uncomment the rest of my code and everything worked again.
The issue kept popping up over and over in PyCharm. So I created a new project and loaded the needed script. Then I provided the directory to path and assigned the default Python version that I wanted to use... and it worked. Then I was able to finally use "execute line in console" once again.
I had this problem because I renamed my project, it was "xx" I renamed it to "yy", what I did was I went through the directory of .idea in the "yy", in any of those files (all XML files) if there were the name "xx", I replaced it with "yy"
I experienced this problem after moving my project to a different root directory. None of the above solutions worked for me.
I solved it by opening my entire project folder, instead of just the python file I was trying to run. And then running the file I wanted, while the entire project was loaded into PyCharm.
open the qtdesigner work dictionary setting and choose your project path then click OK, don't not use the mysterious work dictionary path by default
In my case Run -> Edit Configuration didn't help.
I've solved it changing the value of "WORKING_DIRECTORY" attribute in .idea -> workspace.xml
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/your/correct/path/here" />
I am a beginner so appreciated this 6 year and 6 month discussion. I couldn't add a comment. I setup PyCharm 2022.1.1 and a Python 3.10.4 virtual environment with pyside2 and pyside6 on Ubuntu 22.04. I tried all the suggestions above and could get none of them to work for me. Following these instructions: https://pythonpyqt.com/how-to-install-pyqt5-in-pycharm/ both pyside2-designer (Qt5Designer) and pyside6-designer from my virtual environment were added as external tools. pyside2-designer failed with the working directory error and pyside6-designer worked without any error. Looking closer at pyside2-designer selecting the working directory with the browse button, I still could not create file - exit code was 127 - but the Qt5 Designer was available for existing ui files. I used pyside2 because PyQt5-tools could not be pip installed in my python3.10.4 virtual env.
This worked for me on PyCharm 2021.3.2:
This problem has been driving me nuts. I am trying to import a class from a file in the same directory. PyCharm is giving me the "Unresolved reference" error. MyClass is defined in file.py.
I have found these questions:
Unresolved reference issue in PyCharm
Pycharm: "unresolved reference" error on the IDE when opening a working project
PyCharm shows unresolved references error for valid code
Unresolved reference when importing from sibling sub-package with
I have the following project structure:
I have marked src as the sources root...
I have set the "Add source roots to PYTHONPATH":
I have tried File -> Invalidate Caches / Restart.. (I even restarted the computer).
If I try to run it, I get the following error in the console: ImportError: cannot import name 'MyClass'
The interpreter is a virtualenv on Python 3.4 on Ubuntu x64 14.04.
If I install and import any 3rd party packages, they work fine.
If I try echo $PYTHONPATH in the terminal it returns nothing (same with env | grep PYTHONPATH. I have the appropriate virtualenv active when I try these.
Any clues?
If MyClass is defined in pack/file.py, you need to import it as:
from pack.file import MyClass
Note that using names of Python built-in types (such as file) for your own modules is a bad idea.
If you are using python version 3 try this
from .pack import myclass
This worked for me
The following steps solved my issues:
All directories required at least a blank __init__.py file
Mark all directories as source roots (per previous poster instructions)
Yes, if you are using python 3 you should add something like this:
from .pack import MyClass
It will work
I had the same issue when I tried to import a new class, however I could successfully import functions from a file in the same directory. I still dont understand why I could not import my class but thought I would share the information for other users.
#kaylebs response worked for me. However I then added the src directory to the list of source directories, first link in #lulian 's question and could remove the '.' from my file name.
There are several reasons why this could be happening. Below are several steps that fixes the majority of those cases:
.idea caching issue
Some .idea issue causing the IDE to show error while the code still runs correctly. Solution:
close the project and quick PyCharm
delete the .idea folder where the project is. note that it is a hidden folder and you might not be aware of its existence in your project directory.
start PyCharm and recreate the project
imports relative not to project folder
Relative imports while code root folder is not the same as the project folder. Solution:
Find the folder that relative imports require in the project explorer
right click and mark it as "Source Root"
Editor not marking init.py as Python
Which is the most illusive of all the cases. Here, for some reason, PyCharm considers all __init__.py files not to be python files, and thus ignores them during code analysis. To fix this:
Open PyCharm settings
Navigate to Editor -> File Types
Find Python and add __init__.py to the list of python files or find Text and delete __init__.py from the list of text files
I just delete the copied the code and delete the file and again create the same, that time it will work
I have a project located at /home/myself/workspace/Project1, for which I created an SDK from a Python 2.7.3 Virtualenv I have setup.
This project uses some external code that I have in an accessible directory, e.g. /home/myself/LIBRARY; this directory contains several directories with code, docs etc....
For example, there is a module "important_util" located at /home/myself/LIBRARY/mymodule/important_util.py.
Now, I added the whole dir /home/myself/LIBRARY in the SDK Classpath, and in the Editor window it appears just fine. The imports and calls are recognized and I can also navigate through the code in LIBRARY directories.
The problem is that, when I try to run my program, it fails at the first import using LIBRARY!!!
Traceback (most recent call last):
File "/home/myself/workspace/Project1/my_program.py", line 10, in <module>
from mymodule import important_util as ut
ImportError: No module named mymodule
I also tried to add the same directories to the section "Global Libraries" in the Sources section...but no luck.
I can't seem to find a way to add this code to the Run classpath, how would I be able to do this?
Make sure you have __init__.py in mymodule directory:
The __init__.py files are required to make Python treat the
directories as containing packages; this is done to prevent
directories with a common name, such as string, from unintentionally
hiding valid modules that occur later on the module search path. In
the simplest case, __init__.py can just be an empty file, but it can
also execute initialization code for the package or set the __all__
variable, described later. ©
UPDATE: In IntelliJ IDEA additional directories should be added as Module Dependencies or configured as Libraries (to be added to the Dependencies) instead of the Classpath tab of the Python SDK:
I've verified that this folder (D:\dev\lib) is added to the PYTHONPATH and import works.
In IntelliJ 14 it's a little different, you are modules/eggs like so:
Go to File -> Project Structure
Now select Modules and then "Dependencies" tab
Click the "+" icon and select "Library"
Click "New Library" and select Java (I know it's weird...)
Now choose multiple modules / egg and "OK".
Select "Classes" from categories.
Give your new library a name, "My Python not Java Library"
And finally click "Add Selected"
From Version of 2017.1 adding it has been changed again. There is no project structure in the file menu. Writing current procedure down:
Go To Preference/Settings. File -> Settings (IDE Name -> Preferences for macOS)
Select Build, Execution, Deployment
Select Python Interpreter
Select on drop-down menu of project interpreter and select the path of path of version of Python required for the project.
Click on Apply and wait for few minutes to let IntelliJ index the python packages.
All error should be gone now and You should be able to see Python used in the project in the list of external libraries.
Happy Coding.