Can't call a function from another file in python - 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'.

Related

No such file or directory

I am trying to use Pillow Library in Python. I am writing basic code to open up a picture that I have saved.
But every time I run the code, it says
"can't open file 'C:\Users\saadn\PycharmProjects\Giraffe\main.py':
[Errno 2] No such file or directory".
The path for where the picture is saved is "C:\Users\saadn\PycharmProjects\Giraffe\DirectoryAssign1"
Now I know that in the error it says "Girrafe\main.py". but I don't have a python file named main at all. Someone guide me.
the code I wrote was
from PIL import Image
img = Image.open("dany.jpg")
img.show()
Here is a screenshot for better understanding.
Actually I think there are 2 issues, and not 1.
Error 1 - Wrong File is being tried to run :
In the picture you attached there is an error which means it cannot open main.py (No such file) . You entered a wrong file name, your file name is OpenAndShow.py
How to fix?
Be sure to open the terminal or command prompt and be sure you are in the following directory C:\Users\saadn\PycharmProjects\Giraffe\ and enter the following command as you are a Windows OS User:
py OpenAndShow.py
Fun fact: Of course Python won't search in the whole PC or directory (including folders which are in the directory) , so that's why you need to mention it is in a folder in the Giraffe folder!
Error 2 - Wrong location for the picture
If you had fixed error 1, you will get another error, that dany.jpg is not such file, why ? Because it is in another folder inside the folder your code is located, you can use dany.jpg when they are in the same folder, not in another folder in the same folder, in this case, it is in DirectoryAssign1 which is in Girrafe folder.
How to fix?
To fix it, change the path:
From : The current Path:
dany.jpg
To : The following path below:
DirectoryAssign1\dany.jpg
You are running the wrong file. In PyCharm, afaik you can right click on the file and run. Your PyCharm is now trying to run the file main.py.
Otherwise, you can use the terminal:
python OpenAndShow.py

How to import from other scripts in VSCode?

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.

Python run external lib class directly from command line

So imagine i have an external lib called printer with one file that looks like this.
# in file ExternalLibPrinter.py
def main():
print("hello external lib")
if __name__ == "__main__":
main()
Now i've installed this via pip.
What I would like to do is run that main function. If this was a python file that in my directory i would simply run
python3 ExternalLibPrinter.py
but I cant find such a file. I've also tried
python3 printer/ExternalLibPrinter.py
This can't find that file either. So is this not possible?
Use this code to call the main function :
import printer.ExternalLibPrinter as printer
printer.main()
If however the main() function was in the module's __init__.py, you would call it this way :
import printer
printer.main()
If you want to know where are the library's files stored, do this :
$ python3
>>> import printer
>>> printer
<module 'printer' from '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/printer/__init__.py'>
In this example it shows where printer is installed on my computer, but that may be different with yours.
If the library is a single file, it will be called printer.py. If is is in multiple files, there will be a directory named printer which will contain :
__init__.py — File that is used when you write import printer
and for each submodule there will be a file submodulename.py that is used when you write import printer.submodulename.

Python module import statement runs in PyCharm but not in VSCode

Here's my file structure
test/
-dir1
-thing.py
-dir2
-__init__.py
-thing2.py
I am using python 3.7 and windows 10.
In thing.py, I'm trying to import a function called foo from thing2.py and have it execute when I run thing.py. My code works perfectly in PyCharm when I press run. However, when I run thing.py from the terminal directly or through code runner in VSCode, I get the following error:
from dir2.thing2 import foo
ERROR: ModuleNotFoundError: No module named 'dir2
Is the issue something to do with my PYTHONPATH or something else?
Based on the information you provided, I reproduced the problem you described. And you could use the following methods to solve it:
Please add the following code at the beginning of the "thing.py" file, which adds the path of the currently opened file to the system path so that VSCode can find "foo" according to "from dir2.thing2 import foo":
import os, sys
sys.path.append('./')
If you don't want to add code, you could add the following setting in "launch.json", which adds the path of the project when debugging the code:
"env": {
"PYTHONPATH": "${workspaceFolder}"
}

Python import module give blank output

I have a file named task.py with the below code
def add(a,b):
c = a+b
return c
and another file named inputs.py with the below code
import task
a = task.add(2,2)
print(a)
When I run this code, it shows a black output with no errors. Both the files are present under the same directory.
Can anyone confirm why it does not show any outputs?
This worked after i had the Python file and Pycharm file in under C directory.
Python scripts must be in current working directory. You can check CWD using following code:
import os
os.getcwd()
The problem is specific to your system.
I have tried and it worked fine for me
Try the following :
Running again
delete pycache
run by pressing run button in your code editor
run by python inputs.py

Categories

Resources