Return function value instead of string - python

It's weird, but it never happened to me before, so I do not know where I'm wrong.
I have this script:
import PyEngine
PyEngine.init()
print(PyEngine.info.pack)
The __init__ of PyEngine is this at the moment:
import subprocess, sys
class init():
def __init__(self):
__checkp__ = subprocess.check_output([sys.executable, "-m", "pip", "freeze"])
self.__packages__ = [r.decode().split("==")[0] for r in __checkp__.split()]
self.__pack__ = " ".join(self.__packages__)
print(self.__pack__)
self.__info__ = info(self)
class info():
def __init__(self, main):
self.__pye__ = main
def pack(self):
return self.__pye__.__pack__
With print(self.__pack__), I get this:
Django Jinja2 MarkupSafe PyOpenGL PyTMX PyYAML Pygments Vector2D WMI attrs euclid future glsvg inputs keyboard pbr pyPEG2 pygame pyglet pygobject pyperclip pytz qutebrowser six stevedore tmx virtualenv virtualenv-clone virtualenvwrapper wheel
But with print(PyEngine.info.pack), I get this:
<function info.pack at 0x0000000003072A60>
I can not understand...
Also, I would like to know how I could, if I wanted to, use the super class. Despite having tried so many times on this subject, honestly even now I can not fully understand how it works.

Related

Python3 import class if module requirements met

I am looking for a way to add soft requirements to my python module.
My module will use some external pip resources that the user may or may not install depending on their use case. I would like this to be an option rather than a requirement but a big chunk of code will require the external modules. I simply want to return an error if a class is used that does not have the correct module installed.
example:
#tkc_ext.py
try:
from tkcalendar import DateEntry
tkc_imported = True
except:
tkc_imported = False
class tkcNotImportedError(Exception):
def __init__(self):
print("tkcalendar module is not installed.\n please install it to use these widgets")
class cDateEntry(DateEntry):
def __init__(self, master, **kwargs):
if not tkc_import:
raise tkcNotImportedError
##insert code here
I'm not sure how I can disable the cDateEntry class if tkcalendar has not been installed as it will error on the class line due to DateEntry not being imported, and i cant error out before that as it will simply error if the file is imported.

PyCallGraph's GlobbingFilter does not work?

I am using pycallgraph (from within a jupyter notebook) to understand the codebase I'm working on. For some reason, the GlobbingFilter does not seem to work - I can't exclude things using the GlobbingFilter
from pycallgraph import PyCallGraph, Config, GlobbingFilter
from pycallgraph.output import GraphvizOutput
from PIL import Image
import numpy as np
gv = GraphvizOutput()
gv.output_file = 'basic2.png'
config = Config()
config.trace_filter = GlobbingFilter(
exclude=['pycallgraph.*', '*__init__*'], include=['__main__'])
class Apple:
def __init__(self):
pass
def eat(self):
pass
class Basket:
def __init__(self):
self.content = []
def add(self, other):
self.content.append(other)
with PyCallGraph(output=gv, config=config):
a = Apple()
b = Basket()
b.add(a)
b.content[0].eat()
Image.open(gv.output_file)
The output image contains the __init__ methods. Any ideas on how to remove them? In addition I also can't exclude classes and their children (eg. Apple)
Ps. I'm using callgraph4py (a mantained fork if pycallgraph)
It was a simple fix - the version if the library I installed had the GlobbingFilter functionality commented out.
See line 208 here: https://github.com/e-alizadeh/pycallgraph/blob/master/pycallgraph/tracer.py
Uncommenting lines 208 & 209 fixed my issue.

How to install cairo and rsvg for python

I understand that Stackoverflow is for help with code, but I figured I'd ask anyways.
I found from the post here that it is possible to put a .svg file into a tkinter window, but after days of searching, I still can't find any place where I could install cairo and rsvg from.
I am currently using Windows 10 with python 3.6.
EDIT:
I have found out how to install cairo and rsvg. Cairo is working but
rsvg is not. I have managed to put SVGs in Tkinter with cairo and not rsvg, though. For
anyone curious about this, you may want to check post out:
Putting .SVG images into tkinter Frame.
Thanks in advance.
Edit: Ok, so pip won't work for installing pycairo. Found that out.
And the other options haven't worked for me either. I am about to be
away from my computer, but I'll give you some of the things I found.
This
This
and
This
Sorry I couldn't be more help. Hope you figure it out!
First, use pip install pycairo
Unfortunately, rsvg is unavailable for windows, but cairographics.org have a simple wrapper.
Save the following as rsvg.py in the same folder as your script:
#some code to give rsvg.render_cairo(ctx) ability
#on windows.
import os
try:
import rsvg
WINDOWS=False
except ImportError:
print"Warning, could not import 'rsvg'"
if os.name == 'nt':
print "Detected windows, creating rsvg."
#some workarounds for windows
from ctypes import *
l=CDLL('librsvg-2-2.dll')
g=CDLL('libgobject-2.0-0.dll')
g.g_type_init()
class rsvgHandle():
class RsvgDimensionData(Structure):
_fields_ = [("width", c_int),
("height", c_int),
("em",c_double),
("ex",c_double)]
class PycairoContext(Structure):
_fields_ = [("PyObject_HEAD", c_byte * object.__basicsize__),
("ctx", c_void_p),
("base", c_void_p)]
def __init__(self, path):
self.path = path
error = ''
self.handle = l.rsvg_handle_new_from_file(self.path,error)
def get_dimension_data(self):
svgDim = self.RsvgDimensionData()
l.rsvg_handle_get_dimensions(self.handle,byref(svgDim))
return (svgDim.width,svgDim.height)
def render_cairo(self, ctx):
ctx.save()
z = self.PycairoContext.from_address(id(ctx))
l.rsvg_handle_render_cairo(self.handle, z.ctx)
ctx.restore()
class rsvgClass():
def Handle(self,file):
return rsvgHandle(file)
In your script, do from rsvg import * and when you need to use it, run:
rC = rsvgClass()
h = rC.Handle("YOUR-FILE-HERE.svg")
s = cairo.ImageSurface(cairo.FORMAT_ARGB32, 100, 100)
ctx = cairo.Context(s)
h.render_cairo(ctx)

'AttributeError: module 'usbiss' has no attribute Aclass' when creating class instance

Trying to write a python package and I cant create an instance of a class in one of my source files.
package layout is:
-packagedir
----README.md
----setup.py
----packagename
--------__init__.py
--------package.py
--------modules
------------file1.py
------------file2.py
in init.py within packagename i have:
from . modules import file1
from . modules import file2
The file file1.py contains a class:
class File1():
def __init__(self):
self.val = 0
# Other methods and such
The file file2.py contains a class:
class File2():
def __init__(self):
self.type = 0
# Other methods and such
and in package.py I have a class as thus:
class Aclass(file1.File1, file2.File2):
def __init__(self):
# nothing important in here yet
I have build and installed my package like this:
python3 setup.py sdist
sudo pip3 install dist/package-0.1.tar.gz
Now I create a file called test.py and put in it the following:
import package
iss = package.Aclass()
when I run the test file i get the following error:
AttributeError: module 'usbiss' has no attribute 'Aclass'
I do not understand why it is that python is not letting me create an instance of class Aclass and thinks I am accessing an attribute. I am sure there is something fundamentally wrong with my import statements or something but i am at a loss as to what it is. How do I correct this so that I can create an instance of Aclass and use its methods?
Thanks.
The problem here was that I was importing the package itself but not a module within that package. I changed my import in test.py to:
from package import package
and this fixed my issue.
Are you sure you are handling your import properly and not introducing any circular dependencies?
Also:
def __init__(file1.File1, file2.File2):
def __init__():
Your init methods are lacking self. They should be:
def __init__(self, file1.File1, file2.File2):
def __init__(self):

How to write a post install script which adds the installed program to Windows path? (Python)

This seems to show how to set up a post install script, but I am still unclear on how to use it to add the installed directory to the path.
Which values (and where can I find them) do I need to get from the install and how can I refer to them in the post install script itself?
Here is what I have so far, all stolen from other places and stuck together, don't know how to make it work:
import _winreg
import os
from distutils.core import setup
from distutils.command.install import install as _install
REG_PATH = r"SOFTWARE\my_program\Settings"
def _post_install(dir):
if os.name == 'nt':
try:
_winreg.CreateKey(_winreg.HKEY_CURRENT_USER, REG_PATH)
registry_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, REG_PATH, 0,
_winreg.KEY_WRITE)
_winreg.SetValueEx(registry_key, name, 0, _winreg.REG_SZ, value)
_winreg.CloseKey(registry_key)
return True
except WindowsError:
return False
class install(_install):
def run(self):
_install.run(self)
self.execute(_post_install, (self.install_lib,),
msg="Running post install task...")
setup(cmdclass={'install': install})

Categories