Python - importing other python programs as libraries - python-3.x

I am using FreeCAD.
FreeCAD offers many libraries as .so files.
Therefore, to use them, i just have to modify .bashrc, in order to include in the PYTHONPATH, the location of the library files.
Then it is all a matter of doing import FreeCAD and this works.
This is all vanilla right now.
However, there is another library that i cannot import.
When i type import Draft, i get that
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'Draft'
I looked up and there is no Draft.so in the library directory.
However, in the program's GUI - python console when i type import Draft it works.
I investigated why this happens. I typed:
import Draft
import inspect
inspect.getfile(Draft)
And i got:
'/usr/share/freecad-daily/Mod/Draft/Draft.py'
This is another directory.
There is even another folder in this directory, that contains all the Draft function calls, as separate python files.
(For example there is a method called Draft.scale(). Inside the directory there is a file called scale.py)
Is there a way to include all these python files, so i can use import Draft, and just works?
Perhaps is it a matter of setting a new PYTHONPATH?

Just add '/usr/share/freecad-daily/Mod/Draft' to your PYTHONPATH
In general, each subdir inside Mod is a package root.

Related

Python Relative Imports but I copied the documentation

I read all the other SO posts about this and it either doesn't work or uses sys.path.append.
Below is a replica of the official documentation:
All other files not shown are empty
moduleA.py
from ..subB.moduleB import MyClass
moduleB.py
class MyClass:
def __init__(self):
pass
package/subB/__init__.py
from .moduleB import MyClass
Traceback from running moduleA.py
Traceback (most recent call last):
File "path\to\my\projects\folder\package\subA\moduleA.py", line 1, in <module>
from ..subB.moduleB import MyClass
ImportError: attempted relative import with no known parent package
File Structure
The Python docs unfortunately forget to mention that their example only works if you run your code in a very specific way using the '-m' switch. So you would have to do python -m subA.moduleA and you need to ensure that your current working directory is package. Otherwise it will fail.
If you don't like these restrictions (like me), I've created an experimental import library: ultraimport
It gives you more control over your imports and lets you do file system based imports.
In moduleA.py you could then write:
import ultraimport
MyClass = ultraimport('__dir__/../subB/moduleB.py', 'MyClass')
This will always work, no matter how you run your code or what is your current working directory. Also no need to change sys.path. It will actually go to the file system and load the very file you've specified.

Import script in sub directory not working... Blender Add-On

I have a folder structure like this:
C:
|_Blueprint
│ main.py
│
└───toolbox
blueprint_tools.py
When I run this code in Blender's scripting text page:
from toolbox.blueprint_tools import dimension, array, modify
I get an error in the console
Traceback (most recent call last):
File "\main.py", line 20, in <module>
ModuleNotFoundError: No module named 'toolbox'
Error: Python script failed, check the message in the system console
I swear, when I run this code (on other projects) outside of Blender this structure and code runs fine. But I get an error when running this script in Blender for testing out my Add-On.
If I compile the Blueprint folder into a .zip and install it everything works fine.... ??
I'm lost, could anyone please help me.
If I run the code like this: (added a . before toolbox for CWD)
from .toolbox.blueprint_tools import dimension, array, modify
Traceback (most recent call last):
File "\main.py", line 20, in <module>
ImportError: attempted relative import with no known parent package
Error: Python script failed, check the message in the system console
Both your error traces write File \main.py ... which means that Blender considers your main.py file to be in the root folder, knowing nothing about its real location in the file system hierarchy.
When you installed your structure as a zip file, you provided all necessary info to Blender.
Addendum:
Temporarily, during developing / debugging your add-on, you may add the full path (for finding your toolbox.blueprint_tools module) to the sys.path variable.
There are 2 possibilities how to do it:
Insert into your main.py file these commands (use the path to your parent folder of your toolbox folder, of course):
import sys
sys.path += [r"C:\Users\Davi\Documents\Python\PARENT_of_toolbox"]
before your statement
from toolbox.blueprint_tools import dimension, array, modify
command, or
Insert into your main.py file these commands (use the path to your toolbox folder, of course):
import sys
sys.path += [r"C:\Users\Davi\Documents\Python\PARENT_of_toolbox\toolbox"]
before your modified statement
from blueprint_tools import dimension, array, modify

relative imports on CDSW

I have a project on CDSW organized as follow :
/home/cdsw/my_project_v2.1
|_>input
|_>output
|_>scr
|_>__init__.py
|_>main.py
|_>utils
|_>__init__.py
|_>helpers.py
in my current code, I use sys.path.append to perform my imports.
import sys
sys.path.append("/home/cdsw/my_project_v2.1/src/utils/")
from helpers import bar
This works fine but it is a bad practice because if the version change, then I need to change all my scripts that use the path.
I wanted to replace it with some relative path :
from .utils.helpers import bar
But I got the error :
$ pwd
/home/cdsw
$ python3 my_project_v2.1/src/main.py
Traceback (most recent call last):
File "my_project_v2.1/src/main.py", line 1, in <module>
from .utils.helpers import bar
ModuleNotFoundError: No module named '__main__.helpers'; '__main__' is not a package
what do I need to change in my architecture or in my code to make it work ?
Just use
from utils.helpers import bar
A short excerpt from the documentation of the Python command line arguments:
If the script name refers directly to a Python file, the directory containing that file is added to the start of sys.path, and the file is executed as the __main__ module.
The first half of the sentence means that you can use absolute module names when referring to the contents of your directory, because Python will search for module there. The fact that you can not use relative imports is a consequence of the second half of the sentence.
As a side note, you may also consider omitting the version number from the name of the directory, or better yet, put your code directly in /home/cdsw. The latter may sound strange as you would never do that on a regular machine, but here everything is in a container and actually this is the way your code is supposed to be organized in CDSW. You can confirm this by creating a new project based on a template or a git URL – both will put code directly in the home directory.

Zipline import error. No module named zipline.transforms

I am not able to import the zipline.transforms module
>>> from zipline.transforms import batch_transform
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'zipline.transforms'
Disclaimer: I'm currently a maintainer of Zipline.
I'm guessing the reason you're seeing this error is because that particular module was removed a while back (assuming you're using zipline 1.0.0 or later). If you want to do things similar to transforms you'll need to call data.history() to get your pricing data, and call numpy/pandas functions like .avg() or .std(), or use talib.
I think you should firstly print out your sys.path (print sys.path), and then see where you zipline module is installed (somewhere like .../lib/python2.7/site-packages/zipline). Usually "no module named XXX" is caused by you sys.path doesn't contain the path you installed zipline. You should just add your zipline path into sys.path. Also use anaconda is good for zipline (http://www.zipline.io/install.html), so as to keep the environment tidy and clean.

Imports not found when running script outside of Pycharm?

I have a project structured this way...
main.py imports scripts from subfolders like so:
from controllers.available_balances_controller import available_balances_controller
Subfolders:
models
views
controllers
When running main.py in Pycharm it works find.
When I try to run in terminal I get import errors:
Traceback (most recent call last):
File "main.py", line 6, in <module>
from controllers.available_balances_controller import available_balances_controller
ImportError: No module named controllers.available_balances_controller
Am I importing the scripts wrong in main.py?
What is the proper way to do the importing?
Try running your script with the -m flag:
$ python -m main
That means that you are running your main.py as a module inside a python package, not as a simple script. PyCharm makes it easy for you by assuming so when you create a project. When you are in the terminal, you need to specify it yourself. You don't need __init__.py files inside your directories in Python3.
Check out:
https://docs.python.org/3/reference/import.html
Relative imports in Python 3

Resources