I am trying to import a function called page1 that contains other functions inside of it in a library file so that I can call it inside this file. However, this creates the following error:
Traceback (most recent call last):
File "/Users/antonios/numworks-math-libs/numworksMath.py", line 1, in <module>
import numworksLibs
File "/Users/antonios/numworks-math-libs/numworksLibs.py", line 1, in <module>
from numworksMath import page1
File "/Users/antonios/numworks-math-libs/numworksMath.py", line 35, in <module>
page1()
File "/Users/antonios/numworks-math-libs/numworksMath.py", line 29, in page1
numworksLibs.get_ordered_pair(ordered_pair_num, xs, ys)
AttributeError: partially initialized module 'numworksLibs' has no attribute 'get_ordered_pair' (most likely due to a circular import)
I think this is because the main script is importing the library, and the library is importing the main script (circular import). Is there a way that I can get around this in Python? I have tried all solutions from this website and made sure that none of the names conflicted with any Python built-in libraries, as previously mentioned in other posts on SO. get_ordered_pair is also defined in the library file.
library file import:
from numworksMath import page1
a snippet of the main script:
import numworksLibs
def page1():
page1 contains code that will run if the function is called without an input, and this happens when importing the file from the Python CLI.
You can guard your code by checking if the file is being run as a script or if it's being imported as a module. To do this you need to check if the current __name__ is set to '__main__'.
If your file looks like this:
def foo():
...
foo()
Simply change it to only run foo when __name__ is '__main__'
def foo():
...
if __name__ == '__main__':
foo()
Now foo will only automatically run if you call python on the file directly, and not if it is simply imported.
What you would really want to do in this situation is to create a separate file like #Carcigenicate mentioned. with all the code that you are importing more than once and have each script import this. For me, I made a file called main.py with all the code that needed to be imported more than once, and then both the library file and the main script importing this file.
Related
In github there are four py Data which I put on my PyCharm. When I run main.py I get this message:
/Users/Armut/Desktop/High_D/Coursera/bin/python /Users/Armut/Desktop/High_D/main.py
Traceback (most recent call last):
File "/Users/Armut/Desktop/High_D/main.py", line 6, in <module>
from data_management.read_csv import *
ModuleNotFoundError: No module named 'data_management'
Here is a screenshots:
Can someone help, what I am doing wrong or how can I fix it?
EDIT (Put folders):
/Users/Armut/Desktop/High_D/Coursera/bin/python /Users/Armut/Desktop/High_D/main.py
WARNING:root:Failed to import geometry msgs in rigid_transformations.py.
WARNING:root:Failed to import ros dependencies in rigid_transforms.py
WARNING:root:autolab_core not installed as catkin package, RigidTransform ros methods will be unavailable
Traceback (most recent call last):
File "/Users/Armut/Desktop/High_D/main.py", line 7, in <module>
from visualization.visualize_frame import VisualizationPlot
ModuleNotFoundError: No module named 'visualization.visualize_frame'
EDIT:
/Users/Armut/Desktop/High_D/Coursera/bin/python /Users/Armut/Desktop/High_D/src/main.py
Traceback (most recent call last):
File "/Users/Armut/Desktop/High_D/src/main.py", line 7, in <module>
from src.visualization.visualize_frame import VisualizationPlot
File "/Users/Armut/Desktop/High_D/src/visualization/visualize_frame.py", line 10, in <module>
from utils.plot_utils import DiscreteSlider
ModuleNotFoundError: No module named 'utils.plot_utils'
Edit (No errors, but I just get a blank picture):
Edit (I installed matplotlib 3.0.3 and got this):
The issue here is, that it is just a picture. If you can see there are buttons like "next". I should be able to click it so I can track it. But how does it work?
Do the following
from read_csv import *
import visualize_frame as vf
The reason why it was not working for you is because you were importing files that dont exist on your system. When you do from data_management.read_csv import *, what you are telling the Python interpreter to do is to search for a folder called data_management inside you're Coursera folder and get everything from read_csv.py.
This is the same case with visualize_frame. Since you have a flat directory structure, you dont need the folder names. You can directly import the .py files as is.
Another thing to note here is that I personally wouldn't do from read_csv import * because I will be flooding my namespace with a lot of things I probably wont use. I would rather use import read_csv as any_alias_you_like. This way I only fill my namespace with what I want by doing the following
x = any_alias_you_like.function_call()
The reason why I didn't do this with the main code solution is because I am not sure where all you are using read_csv functions and classes in your code and if that is not accounted for by prefxing the alias name properly, you will run into a multiple errors. So my advice is to identify all the funcutions/classes that you are using in read_csv.py and prefix them properly with an alias.
I also used the import statement for the visualize_frame differently. This is because, when you do a from import..., you are only partially initializing the module. However, a proper import visualize_frame will ensure that your entire module is initialized in one call and you can use everything it offers by simply prefixing the alias.
Read about the difference between from import and import... here.
Read about how Python searches for libraries here.
Even after googling, trying a million things etc, I just can't get package importing to work properly. I have a simple folder structure like this:
(main folder)
---------------
funktio (folder)---->| __init__.py |
main.py | tulosta.py |
country_data.py ---------------
Basically I'm trying to import tulosta.py into main.py. Tulosta.py has a function that prints certain stuff from country_data.py. So far the program works when I paste the contents of tulosta.py into main.py and scrap the import of tulosta.py from main.py (so the script reads from country_data properly). I'm doing a school assignment and it requires importing a module and a package. My problem is, if I try to
import funktio.tulosta
I only get
Traceback (most recent call last):
File "E:\Kouluhommelit\Script-programming\moduuliharkka\main.py", line 4, in <module>
tulosta.tulosta()
NameError: name 'tulosta' is not defined
and if I try to put "from tulosta import tulosta" into the init file, I get
Traceback (most recent call last):
File "E:\Kouluhommelit\Script-programming\moduuliharkka\main.py", line 1, in <module>
import funktio.tulosta
File "E:\Kouluhommelit\Script-programming\moduuliharkka\funktio\__init__.py", line 1, in <module>
from tulosta import tulosta
ModuleNotFoundError: No module named 'tulosta'
So basically whatever I try I get an error code. Here's the code from main.py:
import funktio.tulosta
import country_data
tulosta.tulosta()
and tulosta.py:
def tulosta():
for code in country_data.countrycodes:
print (country_data.codemap[code], ':\n\t','Head honcho:', country_data.countries[country_data.codemap[code]]['head honcho'],'\n\t','Population:', country_data.countries[country_data.codemap[code]]['population'],'million')
I'm really getting desperate after struggling with this for 4+ hours already. It seems like such a simple operation, but apparently it isn't. Please help. I'll provide more info if needed.
Here's the assignment:
Rearrange the code from previous exercises:
Make a folder called "moduuliharkka"
Make a python file called "country_data" where you put the lists and dicts from the exercise 15.
Then make a new folder inside the moduuliharkka-folder called "funktio" (tip: init)
Put the code from exercise 16. inside a function and save it as a .py file in the funktio-folder
Go back to your moduuliharkka-folder, make a main.py file where you import the country_data module and the funktio folder as a package
Call the function imported in the main.py script
You need to make one extra call in your main file. Currently, you have imported the file tulosta from funktio, however, you need to access the function/class/variable in that file. tulosta.tulosta() is not including the folder name, which is still needed
In main:
import funktio.tulosta
functio.tulosta.tulosta() #call the function in "tulosta" here
If you do want to call tulosta() as tulosta.tulosta(), import with an alias:
import funktio.tulosta as tulosta
tulosta.tulosta()
I have two scripts, main and statistics. In one script, main, several functions from the other script, statistics, are called. The code is as follows.
if initial_action == "get_portfolio_statistics":
statistics.get_portfolio_status()
statistics.get_current_securities()
statistics.get_open_trades()
Of course, the functions match as far as calling names go, and my IDE (PyCharm) is not giving any warnings. Tests have, refactor after refactor, turned up the fundamentally same error report:
Traceback (most recent call last):
File "G:/stuff/dev/!projects+repositories/RYZ/main.py", line 2, in <module>
import statistics
File "G:\stuff\dev\!projects+repositories\RYZ\statistics.py", line 1, in
<module>
import main
File "G:\stuff\dev\!projects+repositories\RYZ\main.py", line 12, in <module>
statistics.get_portfolio_status()
AttributeError: module 'statistics' has no attribute 'get_portfolio_status'
There are, however, a few intriguing recurrences that have popped up. First of all, in some cases, for no identifiable reason, the tests check out when the function names are changed, however, the results are not consistent with further tests. Second of all, the use of back/forward slashes in the file paths are not consistent, with a G:/ with the first call, and then G:\ for the two latest calls, though the first and latest calls are referring to the same file.
My question is whether this error is a matter of function naming, a matter of file path inconsistencies, a matter of cross-imports, or due to the fact that the functions being called are not housed in a class.
Project Structure:
ryz server backend (RYZ directory)
- main.py
- statistics.py
Import Structure:
# in main.py
import statistics
# in statistics.py
import main
statistics.py Structure:
<imports...>
def get_portfolio_status():
<code>
def get_current_securities():
<code>
def get_open_trades():
<code>
I'll bet it's because of the cross-import. Try to move anything that statistics.py require to that file and then import into and call from main.py.
Your function naming is normal.
I wouldn't worry about the mix of slashes. However, if you're constructing a path yourself, use the os module:
import os
path = os.path.join(os.getcwd(), 'dir', 'filename')
This will ensure that you get a path suited to your platform.
I have a C++ library I would like to bind to Python. I began using Pybindgen, and it is really easy to use, but manually adding functions and namespaces will take a long time considering the size of my C++ library. I've read through the documentation on PyBindGen, specifically, the gccxml portion that supposedly scans header files for me. This would be ideal, yet I can't get it to function properly. Just as a test, I inputted my main header file and tried to export it, but I get this error:
python bindinggenerator.py
Traceback (most recent call last):
File "bindinggenerator.py", line 16, in <module>
main()
File "bindinggenerator.py", line 9, in main
module = module_parser.parse("include\\PhospheneEngine.h")
File "C:\Users\paolo\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pybindgen\gccxmlparser.py", line 598, in parse
pygen_classifier, gccxml_options)
File "C:\Users\paolo\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pybindgen\gccxmlparser.py", line 658, in parse_init
assert isinstance(header_files, list)
AssertionError
And of course my Python code is basically just the modified example from here.
import sys
import pybindgen
from pybindgen import FileCodeSink
from pybindgen.gccxmlparser import ModuleParser
def main():
module_parser = ModuleParser('PhospheneEngine', '::')
module = module_parser.parse("include\\PhospheneEngine.h")
module.add_include("'include\\PhospheneEngine.h'")
pybindgen.write_preamble(FileCodeSink(sys.stdout))
module.generate(FileCodeSink(sys.stdout))
if (__name__ == '__main__'):
main()
I have both gccxml installed and pygccxml (For Python 3.5) installed. The documentation really doesn't say too much about this process, so possibly a quick rundown of how to use this feature would be appreciated.
Thanks in advance.
The parse function takes a list of headers.
module = module_parser.parse(["include\\PhospheneEngine.h"])
I do realize this is a noobish question, but I've been trying for an hour and I can't get it right.
So, I have a Python script which I'd like to modify a bit and play around with as a Python beginner. However, at the very beginning of the script, there's this:
from priodict import priority_dict
Now, I have a file named priodict.py that came with the script. But how do I make it available to the script so it can be included like that?
The Python manual has pages and pages on installing modules, but they all seem to refer to "packages" which are to be placed in certain directories etc. What do I do when I have just the .py file?
I know there is probably a banale one-sentence response to this, but I'm getting frustrated and I'm short on time so I decided to take the easy way out and ask Stack overflow about it.
It seems that, if I don't have the priodict.py file, I get this error:
Traceback (most recent call last):
File "C:\Python27\scripts\dijksta.py", line 192, in <module>
main()
File "C:\Python27\scripts\dijksta.py", line 185, in main
D, _ = dijkstra(G, 1, v)
File "C:\Python27\scripts\dijksta.py", line 139, in dijkstra
Q = priority_dict() # est.dist. of non-final vert.
NameError: global name 'priority_dict' is not defined
If I place the file in the same directory as my script, I get this error:
Traceback (most recent call last):
File "C:\Python27\scripts\dijksta.py", line 2, in <module>
from priodict import priority_dict
ImportError: cannot import name priority_dict
These are the files in question:
https://github.com/kqdtran/ADA1/tree/master/dijkstra
Place the file in the same directory, and that will get you started. Seems you've figured out that much. If all you have is a .py file, that's what you're usually expected to do.
If you're unable to import a name from a module, it usually means that name doesn't exist in that module. Try:
import priodict
print dir(priodict)
Is priority_dict listed? If not, is there a similarly named attribute that might be what you're looking for? It may just be that the instructions given you were misspelled, like the _ wasn't needed.
If it fails on the import line, it may be that there's an error in the module code itself that must be corrected first. you'll get an error telling you roughly where it is.