How to import from other scripts in VSCode? - python

I created the following two scripts in a brand new empty folder called F:\python\hello_world, using Visual Studio Code:
The first is my_function.py:
def hello() -> str:
return "Hello, World"
The second is my_app.py:
from my_function import hello
print(hello())
When I run this from Visual Studio Code, I get an error saying I can't import:
Traceback (most recent call last):
File "f:/python/hello_world/my_app.py", line 1, in <module>
from my_function import hello
ImportError: cannot import name 'hello' from 'my_function' (f:\python\hello_world\my_function.py)
Any clue? I've recently switched from using PyCharm to using VSCode, and I can't quite seem to get started...
New Development
It turns out that, unlike my toy example (which works fine as soon as I add __init__.py to the project's folder), I was trying to run code from within a subfolder of the project. That's a VSCode no-no.

From Python Modules, it said
The __init__.py files are required to make Python treat directories
containing the file as packages.
But without it, your code still works well in my VS Code. You may try resetting VS Code by deleting folders %APPDATA%\Code and %USERPROFILE%\.vscode then see if the error goes away.

Related

Use my own python libraries in visual studio code on raspberry pi

I have a directory that contains sub directories of code that I reuse.
MyBaseDirectory
\genericcodedir1
reuse1.py
\simpleapp1
app1.py
app1.py has the following line
import reuse1
Visual studio will fail to run this since it says it can't find the library.
On windows I simply added the genericcodedir1 to the PYTHONPATH environment variable and all is well.
What should I do on the raspberry pi to allow this to run?
error message:
Exception has occurred: ModuleNotFoundError
No module named 'reuse1'
File "/home/pi/Desktop/Mybasedirectory/simpleapp1/app1.py", line 5, in <module>
import reuse1
I assume you have file structure like this and you open Test folder in VS Code As follows.
You can specify the path by adding the following code above the import statement in app.py:
import sys
sys.path.append("./genericcodedir1")
import reuse1
In addition, you can add the following configuration to the settings.json file to make vscode recognize reuse1.
{
"python.analysis.extraPaths": [
"./genericcodedir1"
]
}
code and result
so if your files looks like :
|_genericcodedir
|_reuse1.py
|_simpleapp1
|_app1.py
you need to add an empty file called __init__.py in your genericcodedir.
another note worthy thing is your working directory (the directory in which your terminal runs)
you may need to append to os path depending on where you are when launching the program

Can't call a function from another file in python

In vscode i have two files in the same folder (main.py and helloworld.py), main importing helloworld and using a function from it, but i get the error "NameError: name 'displayText' is not defined" even though it is a function. The code in main.py is
from helloworld import *
displayText()
and the code in helloworld is
def displayText():
print("Hi")
I know it is an error with vscode because i tried testing it in repl and it worked fine.
As you mention you placed two files in the same folder. it is necessary to check that the file name “helloworld.py” and Imported file name are identical. For your concern please check if the two file extensions are ".py". The error message is shown here the program can not find the function 'displayText'.

Custom modules not read by Python, generating ImportError

I am trying to run a python pipeline through Mac OS Terminal. I am using Python 2.7.15 because newer versions of Python gave me error messages with this file. I keep getting the following error message:
$ python ../../../scripts/gemmaPipeline.py ../../../data/all.fixGL.Q10.ap.bi.MAF5.vcf.gz outfile Results
Traceback (most recent call last): File
"../../../scripts/gemmaPipeline.py", line 5, in
import utils, vcf, genomes100, gemma ImportError: No module named genomes100
The modules listed in the import command are present under the "scripts" folder in a subfolder "modules". For each of the four modules, I have a .py and .pyc file in this subfolder. I cannot get Python to find this path.
I have tried running the same script within a virtualenv but to no avail. I even tried moving the "modules" subfolder to the Python "site-packages" folder in hopes that it would work but failed.
Finally, I tried including an init.py file (blank) in the "script" folder, but that didn't work either.
I am an utter novice and am pretty much learning as I go.Please help.

ModuleNotFoundError error with PyCharm project folder recs

I am working on a project in PyCharm. The project has the following structure:
/projectRoot/
folder1/
somecode.py
utils/
__init__.py
myutils1.py
I'd want to know how I can do an import such that the import works when running the code in the pyCharm console in an interactive manner, as well as when running the code using the
python somecode.py
command in the terminal.
Currently I do:
from utils.myutils1.py import myClass
But command line I get the error:
File "somecode.py", line 10, in
from utils.myutils1 import myClass ModuleNotFoundError: No module named 'utils'
and on PyCharm:
Traceback (most recent call last): File
"/home/ubuntu/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py",
line 2881, in run_code
exec(code_obj, self.user_global_ns, self.user_ns) File "", line 1, in
from utils.myutils1 import myClass ModuleNotFoundError: No module named 'utils'
Any recommendations on the proper folder structure for modules within a project, and how to import them properly?
Thanks!
To explain the answer I recreated that project structure you had
/projectRoot/
folder1/
somecode.py
utils/
__init__.py
myutils1.py
somecode.py
from utils.myutils1 import myclass
if __name__ == "__main__":
print(myclass)
myutils1.py
myclass="tarun"
Running them from pycharm works without any issues, but running them from terminal will produce below error
File "somecode.py", line XX, in <module>
from utils.myutils1 import myclass
ModuleNotFoundError: No module named 'utils'
The issue is that Pycharm does few things for you because which you don't realize why it is not working in the terminal. So before telling you what you need to, I will tell you two things that PyCharm does on its own.
Python Console
When you launch a Python Console from Pycharm, there is some code that gets executed, using preferences.
As you can see there are two options
[X] Add content roots to PYTHONPATH
[ ] Add source roots to PYTHONPATH
And then a starting script as well. So what this does is that it adds the root of your project to python's path. Which is controlled by two main ways sys.path and PYTHONPATH environment variable
If I run the below code in Python Console
>>> import sys
>>> sys.path
['/Applications/PyCharm.app/Contents/helpers/pydev',
'/Applications/PyCharm.app/Contents/helpers/pydev',
'/Users/tarun.lalwani/.virtualenvs/folderstructure27/lib/python27.zip',
'/Users/tarun.lalwani/.virtualenvs/folderstructure27/lib/python2.7', ....
'/Users/tarun.lalwani/.virtualenvs/folderstructure27/lib/python2.7/site-packages',
'/Users/tarun.lalwani/Desktop/payu/projects/folderstructure27']
As you can see '/Users/tarun.lalwani/Desktop/payu/projects/folderstructure27' is added to the Python terminal.
Python Configurations
When you configure to RUN in code using Pycharm, you have similar two options.
We can change the code of our somecode.py to below
import os
print (os.environ['PYTHONPATH'])
import sys
print (sys.path)
/Users/tarun.lalwani/Desktop/payu/projects/folderstructure27
['/Users/tarun.lalwani/Desktop/payu/projects/folderstructure27/folder1',
'/Users/tarun.lalwani/Desktop/payu/projects/folderstructure27', ....,
'/Users/tarun.lalwani/.virtualenvs/folderstructure27/lib/python2.7/site-packages']
From the output we can see that PYTHONPATH is set to current project folder.
Running from terminal
Now let's run the somecode.py from terminal with the modifications we made.
$ python somecode.py
Traceback (most recent call last):
File "somecode.py", line 2, in <module>
print (os.environ['PYTHONPATH'])
File "/Users/tarun.lalwani/.virtualenvs/folderstructure27/bin/../lib/python2.7/UserDict.py", line 40, in __getitem__
raise KeyError(key)
KeyError: 'PYTHONPATH'
So that indicates there is no PYTHONPATH when we ran it in terminal. Let us run it again by removing the print(os.environ['PYTHONPATH']) code. You will get the below output
['/Users/tarun.lalwani/Desktop/payu/projects/folderstructure27/folder1', ...
'/Users/tarun.lalwani/.virtualenvs/folderstructure27/lib/python2.7/site-packages']
Traceback (most recent call last):
File "somecode.py", line 7, in <module>
from utils.myutils1 import myclass
ImportError: No module named utils.myutils1
As you can see folder1 is added to sys.path because it is the folder containing somecode.py, but the root folder has not been added. The fix in terminal is simple, which is to set the root directory path in PYTHONPATH.
PYTHONPATH=`pwd`/.. python somcode.py
And now the code will work from terminal also.
But the way they work are different from Python Console.
IMPORTANT NOTE:
Python Console using PyCharm on remote interpreter.
If running the python console using the remote interpreter option pycharm will fail. This is because it will append the path of the local PC and not the path of the remote server.
In order to fix this problem one has to add a mapping between the local PC directory and the remote server path.
You can use utils package inside folder1 folder:
Then the code will work either way:
from utils.myutils1 import myClass
Similar error here and this appears to be working for me:
Make sure Project Interpreter is set to, for example: C:\Python36\python.exe (in my case) and not a copy somewhere or another.
'File > Settings > Project ____ > Project Interpreter'
Or, long story short, if that route isn't cooperating, can also try finding workspace.xml and manually change SDK_HOME before starting PyCharm:
<option name="SDK_HOME" value="C:\Python36\python.exe" />

Import statement works on PyCharm but not from terminal

PyCharm 2016.2.3, Mac OS X 10.11.1, Python 3.5 (Homebrew);
I have this folder structure
project
/somepackage
/subpackage
__init__.py
bar.py
__init__.py
foo.py
foo.py:
import somepackage.subpackage.bar
print("foo")
bar.py:
print("bar")
So my expected output is
bar
foo
This works fine when run from PyCharm. However, when I run it from my terminal I get an ImportError:
$ pwd
$ /home/project (not the actual path; just omitting some personal stuff)
$ python3.5 somepackage/foo.py
File "foo.py", line 1, in <module>
import somepackage.subpackage.bar
ImportError: No module named 'somepackage'
I have found this question, which is about the same problem. However, none of the suggested solutions work for me, as I am indeed using the same Python interpreter as PyCharm does and I am currently in the folder that contains the /somepackage folder.
Does anyone have any other suggestions about how to solve this issue?
You are running foo.py like a script, but you are really using it like a module. So the proper solution is to run it as a module:
python3 -m somepackage.foo
For the record, another alternative is to edit your path like:
export PYTHONPATH=.
(Or you could put the absolute directory in there, and of course you should append any other directories that are already in your PYTHONPATH.) This is closer to what PyCharm does, but is less philosophically correct.
Setting PYTHONPATH is what makes it work, as noted above. I use the following VSCODE .env content so that it works for any project:
PYTHONPATH=${PROJ_DIR}:${PYTHONPATH}
This is essentially what PyCharm does when you check "Add Content Roots to PYTHONPATH" in your run/debug configuration. It's a helpful setting, but it spoils you because your code fails outside PyCharm.
Or, if you run in terminal, first export:
export PYTHONPATH=...
Took me days to work all this out.
i solved my problem by two steps on Linux:
first step
go to the root directory of your project and set:
export PYTHONPATH=$PATHONPATH:`pwd`
second step
run python3 -m somepackage.foo
remember Without '.py' suffix
I just had the same problem using scapy.layers.http Module,
this problem occurred on my Kali (linux-Debian) but run fine on Win-10 (after few modifications.)
packet was installed (scapy-http) correctly and the program was running in PyCharm but not as script (from terminal)
I tried solving it with reinstalling in main root, and messing with the sys.path but None have worked.
Troubleshoot & Solution
I found that it looks for the http module in:
/usr/local/lib/python3.7/dist-packages/scapy/layers/init.py
and got the ImportError:
from scapy.layers import http --->
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'http' from 'scapy.layers' (/usr/local/lib/python3.7/dist-packages/scapy/layers/__init__.py)
So then I checked where scapy-http is really installed, which is module called http.py, so I just copied it to:
/usr/local/lib/python3.7/dist-packages/scapy/layers/
found the http.py file in :/usr/local/lib/python3.7/dist-packages/scapy_http/
And that did it :)!
I know its a bit glitchie but that worked!

Categories

Resources