Pyinstaller not building the cairo.Context properly - matplotlib

NOTE: I've edited this description and title to include new information during the debugging process.
I have a python application that needs to be converted to an executable. The application draws graphics using the python-gi-cairo package, among others.
The following is an error message in the terminal window, after launching the application:
TypeError: Couldn't find foreign struct converter for 'cairo.Context'
I've already posted separately about making a minimal drawing app that I can test pyinstaller parameters with. Here is a link to that post:
https://stackoverflow.com/questions/73981704/missing-dependency-after-running-pyinstaller?noredirect=1#comment130629339_73981704
here is the evms.spec file:
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(
['evms.py'],
pathex=[],
binaries=[],
datas=[],
hiddenimports=['matplotlib', 'python-gi-cairo'],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False,
)
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
exe = EXE(
pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
[],
name='evms',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
upx_exclude=[],
runtime_tmpdir=None,
console=True,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
)

It turned out there was a missing import statement, (import cairo) which when added, enabled the pyinstaller to build an executable that works great. I'm not sure why the .py version of the application was working without that import.
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk as gtk
from gi.repository import Gdk as gdk
import cairo
from gi.repository import GLib

Related

Different behaviour of dataclass default_factory to generate list

I'm quite new to Python so please have me excused if this question contain some newbie misunderstandings, but I've failed to google the answer for this:
On my personal laptop running Python 3.9.7 on Windows 11 this code is working without errors.
from dataclasses import dataclass, field
#dataclass
class SomeDataClass:
somelist: list[str] = field(default_factory=lambda:['foo', 'bar'])
if __name__ == '__main__':
instance = SomeDataClass()
print(instance)
But when at work running Python 3.8.5 on Windows 10 I get the following error:
File "c:\...\test_dataclass.py", line 13, in SomeDataClass
somelist: list[str] = field(default_factory=lambda:['foo', 'bar'])
TypeError: 'type' object is not subscriptable
I'd like to understand why this behaves differently and what I could do to make it work.
I would expect dataclasses to behave similarly on both computers.
You have already intuited the reason: this is a new feature in version 3.9. You can see it in the What's New article for 3.9 here.
This feature is available in version 3.8 as well, but it is not enabled by default. You can enable it in your code by including this import:
from __future__ import annotations

VCF file is missing mandatory header line ("#CHROM...")

I am getting an error when I am going to read a VCF file using scikit-allel library inside a docker image and os ubuntu 18.04. It shows that
raise RuntimeError('VCF file is missing mandatory header line ("#CHROM...")')
RuntimeError: VCF file is missing mandatory header line ("#CHROM...")
But in the VCF file is well-formatted.
Here is my code of how I applied :
import pandas as pd
import os
import numpy as np
import allel
import tkinter as tk
from tkinter import filedialog
import matplotlib.pyplot as plt
from scipy.stats import norm
GenomeVariantsInput = allel.read_vcf('quartet_variants_annotated.vcf', samples=['ISDBM322015'],fields=[ 'variants/CHROM', 'variants/ID', 'variants/REF',
'variants/ALT','calldata/GT'])
version what Installed :
Python 3.6.9
Numpy 1.19.5
pandas 1.1.5
scikit-allel 1.3.5
You need to add a line like this in the first:
#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT NA00001 NA00002 NA00003
but it's not static for all of the files, you have to make a Header like above for your file. (I suggest try this header first and if it's got error then customize it)

Why can't I use Solver qpsolver anymore?

I just coded a quadratic programming and it has worked very well but after the someday it works not at all.
Does anyone have any idea what the problem is?
My code is:
import time
import numpy as np
from numpy import array, dot
from qpsolvers import solve_qp
Matrix10 = np.load(r'C:\Users\skqkr\Desktop\Semesterarbeit/Chiwan_Q7.npz')
start = time.time()
P = Matrix10['Q'] # quick way to build a symmetric matrix
q = Matrix10['p']
G = Matrix10['G']
h = Matrix10['h']
x = solve_qp(P, q, G, h )>print("QP solution: x = {}".format(x))
print("time :", time.time() - start)
And the result is:
ImportError: cannot import name 'solve_qp' from 'qpsolvers' (C:\Users\skqkr\qpsolvers.py)
I don't understand why it isn't suddenly going well.
I do not think the code you shared is the one you are really using hence it is not easy to understand what is going on. However there are few reason for your problem to happen
The python ImportError: cannot import name error occurs when the import class is inaccessible or the imported class in circular dependence. The import keyword is used to load class and function. The keyword from is used to load the module. For any reason, if the import class is not available in the python class path, The “ImportError: cannot import name” python error is thrown.
The following are the reasons for the ImportError: cannot import name
The import class is not available or not created.
The import class name is mis-named or mis-spelled
The import class name and module name is mis-placed.
The import class is not available in python class path
The import class is not available in python library
The import class is in circular dependency
The python module is just a python file with the .py extension. The keyword from will be used to load the python module. A class in a python module is imported using the keyword import. If the imported class is not in the referred python file, the python interpreter will throw the error ImportError: Cannot import name.
If two python files refer to each other and attempt to load the other file, it will create the circular load dependence. That will cause error in heap memory. If the python interpreter detects the circular dependence, it throws the error ImportError: Can’t Import Name.

Relative imports from within a notebook that is not at the 'main.py' level

I have a structure like the following one:
/src
__init__.py
module1.py
module2.py
/tests
__init__.py
test_module1.py
test_module2.py
/notebooks
__init__.py
exploring.ipynb
main.py
I'd like to use the notebook 'exploring' to do some data exploration, and to do so I'd need to perform relative imports of module1 and module2. But if I try to run from ..src.module1 import funct1, I receive an ImportError: attempted relative import with no known parent package, which I understand is expected because I'm running the notebook as if it was a script and not as a module.
So as a workaround I have been mainly pulling the notebook outside its folder to the main.py level every time I need to use it, and then from src.module1 import funct1 works.
I know there are tons of threads already on relative imports, but I couldn't find a simpler solution so far of making this work without having to move the notebook every time. Is there any way to perform this relative import, given that the notebook when called is running "as a script"?
Scripts cannot do relative imports. Have you considered something like:
if __name__ == "__main__":
sys.path.insert(0,
os.path.abspath(os.path.join(os.getcwd(), '..')))
from src.module1 import funct1
else:
from ..src.module1 import funct1
Or using exceptions:
try:
from ..src.module1 import funct1
except ImportError:
sys.path.insert(0,
os.path.abspath(os.path.join(os.getcwd(), '..')))
from src.module1 import funct1
?

Google colab issue importing ue using different class files

I am trying to use Google colab for my project for which I have to upload a few python files because I need those class files.But while executing the main function.It is constantly throwing me an error 'module object has no attribute' . Is there some memory issue with colab or what! Help would be much appreciated.
import numpy as np
import time
import tensorflow as tf
import NN
import Option
import Log
import getData
import Quantize
AttributeError: 'module' object has no attribute 'NN'
I uploaded all files using following code :
from google.colab import files
src = list(files.upload().values())[0]
open('Option.py','wb').write(src)
import Option
But its always giving me error on some or the other files which I am importing.
The updated version (for a few weeks) can save the files without you having to call open(fname, 'wb').write(src)
So, you only have to upload your 5 files: NN.py, Option.py, Log.py, getData.py, and Quantize.py (and probably other dependency + data) then try importing each one e.g. import NN to see if there's any error.