Python: Can't import a function from another.py file - python-2.7

I have a file named handshake.py. Where there is a function send_data(argument). I want to import that function into another file named siptest.py. I am encountering two problems. I am using microsoft visual studio with windows 7, 64-bit.
1) I can't import function. I have tried using,
from handshake import*
handshkae.send_data(argument)
Which give me an error.
NameError: global name 'handshake' is not defined
Another option I have tried is using
import handshake
handshake.send_data(argument)
Which gives me an attribute error.
AttributeError: 'module' object has no attribute 'send_data'
If I use it the other way, such as
from handshake import send_data
2) MS Visual studio says. No test discovered, please check the configuration settings but I still can run the test somehow. and it says that the test is failed because of Import Error.
ImportError: cannot import name send_data
Both of the said files are in same directory. Plus the function is defined in a class 'TCPhandshake' in handshake.py

One possible reason: there exists reference cycle between module a.py and b.py:
In a.py: import b
In b.py: import a
The solution is to break the cycle. You need to make it clear which module should do what and reduce the dependence.

Make sure both files are in the same directory and try:
from handshake import send_data
If this does not work, try to rename handshake.py file.

Are both handshake.py and siptest.py in the same directory?
If not You can try this:
1) Add __init__.py empty file to the directory that contains handshake.py.
2) Then add the path to that directory to LD_LIBRARY_PATH and PYTHONPATH

make sure the function is in the path
import sys
sys.path.insert(0, '/directory/tothe/handshakefile/')
and then
import handshake

I had the same issue, That happened while I tried to run the program from another directory by using python /home/name/workspace/test.py
Fix I tired.
import sys
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
This need to be added at the beginning.
This works for me.

I find a way to import files in the same directory by implementing keyword as and a object variable for example
import file as fileObj
But the downside is that when you want access to the imported files variable you have to first take fileObj.fileObjVariable.

Try adding/updating the environment variable PYTHONPATH which should point to the folder that has handshake.py

This is very simple, but for me it worked to restart the kernel.

Just make sure the files all are located in the root of the project, then this will work:
import handshake
handshake.send_data(argument)

Related

Custom import package Python

I am making a import package and I keep running into a problem when I try and import and use the package. Primarily when I try to run it.
import mypackage
once I import it I can use it I dont get any errors upon importing it, however when I go to use it I get an error that says
TypeError: 'module' object is not callable
In a folder that I have named myfolder which is located in my current working directory i have a empty init.py file as well as two other .py files which contain the functions i have one called test.py and another called testing.py.... my problem isnt importing them but when I go to use them I get the TypeError.
the folders structure is as follows,
current working directory
-Mypackage
-__init__.py
-test.py
-testing.py
I import it like this,
from Mypackage import test
I use it like this,
test(stuff)
You have to learn how to use modules in python. When you import mypackage into your script it imports a module which has two scripts in it. Let's say they are first.py and second.py . Now if you use something like
from mypackage import first
And then you use a function named func like this
first.func()
Then it should work.
In short either import all the functions from your module or use dot notation to reference these functions. More on module can be read here

Import local module in python

I just change to new company and they use python to dev. When I see the source from ancestors, I see they use sys.path to import local module:
import sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__))+"/folder/")
from folder import module as module
I think it is not right. I suggest them to use package like this:
import path.to.module as module
They ignore my suggest.
Am I right? I google but I don't find any hint for this.
Your method will only work if the module is in your path. Python will add your current working directory to sys.path so it should work for local modules.
However, if you are trying to import a module from another directory, you will likely need to use sys.path.append first
There is an other way is by setting a path to environment variable "PYTHONPATH"

Importerror:No module named in python

I created a file named hello.py in /home/Desktop/problems directory
and i want to import it to a file present in /home/Desktop/PP
#hello.py file
def matrix():
print "enter into matrix"
and i want to access this hello.py file in a file named new.py
so i did like this..
#new.py file
import sys
import os
sys.path.append(os.path.abspath("/home/Desktop/problems"))
from hello import *
matrix()
But i am getting an error like no module named new
Thanks in advance.
UPDATE: The directory order was wrong..so it was giving the error.. it should have been /home/valac/Desktop/problems !!
I created both files with the content described here and I ran your new.py:
python new.py
And it worked just fine. How are you executing or using your new.py script? The problem is probably related to that. Can you explain how are you using new.py?
Do you have init file in the pp folder? You may create init.py under folder pp.
The init.py does not need to contain any code. It will change the folder as a module.

Can't import sqldf in one python file while it works in another. Both files are in different folders. How can I set this right?

In one python file when I try from pandasql import sqldf it works. The path for that is
C:\Users\AmitSingh\Anaconda2\python.exe "C:/Users/AmitSingh/PycharmProjects/HelloPython.py/exercise 2"
In another file when I use the same command it gives me the error
ImportError: cannot import name sqldf
The path for this file is
C:\Users\AmitSingh\Anaconda2\python.exe C:/Users/AmitSingh/Desktop/Data/Udacity/Intro_Machine_Learning/ud120-projects/datasets_questions/explore_enron_data.py
I don't understand why? When I write import sqldf the prompt shows sqldf as an autocomplete option. But doesn't work.
By default, you can't. When importing a file, Python only searches the current directory, the directory that the entry-point script is running from, and sys.path which includes locations such as the package installation directory (it's actually a little more complex than this, but this covers most cases).
However, you can add to the Python path at runtime:
# some_file.py
import sys
sys.path.insert(0, '/path/to/application/app/folder')
import file

Python 2.7 packages and importing between directories

Ok so I've been struggling with this for over a week now and I've tried various methods mentioned on this site and others on google but here goes. I'm running python 2.7. I've got a python script in the parent directory which calls a second script located in a child directory. The second script starts a different thread and does an os.system call to a third and final script. This third script needs to import something located in the parent directory. Can someone tell me what's wrong with this setup? I do have __init__.py located in every folder being used. And I do try adding the relative parent directory to the path. I'm not sure where I'm going wrong.
File Structure
Parent Directory
Python_Script_1.py
Imports_needed.py
__init__.py
Child Directory
Python_Script_2.py
Python_Script_3.py
__init__.py
Method 1
Python_Script_2.py
import os
import sys
import multiprocessing
def listen():
listen_string = "python ~/path/Python_Script_3.py"
os.system(listen_string)
q = multiprocessing.Process(target=listen())
Python_Script_3.py
import sys
sys.path.append("..")
import Imports_needed
ImportError: No module named "Imports_needed"
Method 2
Python_Script_2.py
import os
import sys
import multiprocessing
def listen():
listen_string = "python ~/path/Python_Script_3.py"
os.system(listen_string)
q = multiprocessing.Process(target=listen())
Python_Script_3.py
import sys
sys.path.append("..")
from .. import Imports_needed
ValueError: Attempted relative import in non-package
Question about method 2, how come it's telling me this is not a package despite each directory containing __init__.py?
Additionally, I've used something very similar to method 1 in the past but I cannot see any differences between my code or file structures. If anyone has any suggestions I'd greatly appreciate it. Thanks.
EDIT: Apologies, I forgot something fairly significant in the description. There's a third file involved that I completely forgot about... So sorry :( Python_Script_2 makes a new thread via multiprocessing and does an os.system call to Python_Script_3. Python_Script_3 is located in the same child directory as Python_Script_2. Python_Script_3 is having the import issues when trying to import Imports_needed.py from the Parent Directory. I've updated the question to reflect this. (I'm sorry, I know this is a major detail that I left out but it's a complicated package and doing many more things than just what I'm asking about)
try the following
from Parent_Directory import Imports_needed
or
from Parent_Directory.Imports_needed import <your class or method>
You don't need
sys.path.append("..")
at all. If Python_Script_2.py is imported from the main script, import path inside of Python_Script_2.py will be relative to the main script. So
import Imports_needed
is enough.
Make sure you hava double underscore prefix for the file _init__.py in your child directory (in your example you have only 1 underscore symbol _).
UPDATE
If you rely on sys.path.append(), you should use:
import os
import sys
sys.path.append(os.path.realpath('..'))
otherwise, '..' says nothing to the interpreter about your app environment.