Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 740
Kashif Ahmad Avatar asked Sep 13 '17 07:09

Kashif Ahmad


Video Answer


2 Answers

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 that which module should do what. And reduce the dependence.

like image 67
Jing Chen Avatar answered Sep 18 '22 04:09

Jing Chen


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.

like image 41
Kirin Avatar answered Sep 21 '22 04:09

Kirin