PyMuPDF Pixmap tobytes() returns attribute error - python

I'm following the documentation and using the latest PyMuPDF (1.18.13). However Pixmap.tobytes() isn't working for me:
zoom = 2 # zoom factor
mat = fitz.Matrix(zoom, zoom)
pix = page.getPixmap(matrix = mat)
stream = pix.tobytes(output="png")
AttributeError: 'Pixmap' object has no attribute 'tobytes'
Example of documentation:
What might be the issue here?

I am PyMuPDF's maintainer.
What is your configuration? I just tried your code on Windows and Linux each with v1.18.13 and it work.
Python 3.8.5 (default, Jan 27 2021, 15:41:15)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import fitz
>>> fitz.version
('1.18.13', '1.18.0', '20210505063222')
>>> doc=fitz.open("v110-changes.pdf")
>>> page=doc[0]
>>> pix=page.get_pixmap()
>>> b=pix.tobytes()
>>>
Windows:
Python 3.6.6 (v3.6.6:4cf1f54eb7, Jun 27 2018, 03:37:03) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import fitz
>>> fitz.version
('1.18.13', '1.18.0', '20210505063222')
>>> doc=fitz.open("v110-changes.pdf")
>>> page=doc[0]
>>> pix=page.get_pixmap()
>>> b = pix.tobytes()
>>>

Related

I have problem with import class from another (Python)

The problem is that I can not import class from another folder. Class that I want to import in LoginPage.py.
# login.py
from selenium import webdriver
import time
import unittest
from Selenium.POMProjectDemo.Pages.LoginPage import LoginPage
class loginTest(unittest.TestCase):
#classmethod
def setUpClass(cls):
cls.driver = webdriver.Chrome(executable_path='D:\python\Selenium\chrome_driver\chromedriver.exe')#, options = webdriver.ChromeOptions())
#options.add_experimental_option('excludeSwitches', ['enable-logging'])
cls.driver.implicitly_wait(30)
cls.driver.maximize_window()
def test_01_login_valid(self):
driver = self.driver
driver.get('https://vk.com/')
login = LoginPage(driver)
login.enter_user_name()
login.enter_user_password()
login.login_button
#classmethod
def tearDownClass(cls):
cls.driver.close()
cls.driver.quit()
print('test completed')
#Loginpage.py
from Selenium.POMProjectDemo.Locators.Locators import locators
from auth_data import vk_password,vk_login
from POMProjectDemo.Locators import Locators
class LoginPage():
def __init__(self, driver):
self.driver = driver
self.index_email_id = locators.index_email_id
self.index_pass_id = locators.index_pass_id
self.loginButton_id = locators.loginButton_id
def enter_user_name(self):
self.driver.find_element_by_id(self.loginField_id).clear()
self.driver.find_element_by_id(self.loginField_id).send_keys(vk_login)
def enter_user_password(self):
self.driver.find_element_by_id(self.passwordField_id).clear()
self.driver.find_element_by_id(self.passwordField_id).send_keys(vk_password)
def login_button(self):
self.driver.find_element_by_id(self.loginButton_id).click()
Error:
ModuleNotFoundError: No module named 'Selenium'
The way python figures out import paths is to first look at entries in sys.path and check if the module you are trying to import is accessible from any of the paths. It will stop at the first path under which your module is found.
e.g.
>>> sys.path
['', '/home/bhakta/dev/sonar/controller/venv/lib/python37.zip', '/home/bhakta/dev/sonar/controller/venv/lib/python3.7', '/home/bhakta/dev/sonar/controller/venv/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7', '/home/bhakta/dev/sonar/controller/venv/lib/python3.7/site-packages']
Let's say you have a module called "some_module" in /tmp
➜ ll /tmp/some_module
total 4
-rw-rw-r-- 1 bhakta bhakta 29 Jan 11 11:39 __init__.py
➜ cat /tmp/some_module/__init__.py
def foo():
print("Hello")
➜ python
Python 3.7.10 (default, Oct 19 2021, 17:50:56)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.append("/tmp")
>>> import some_module
>>>
>>>
>>> some_module.foo()
Hello
Now, lets say you have
➜ ll /var/tmp/some_module
total 4
-rw-rw-r-- 1 bhakta bhakta 45 Jan 11 11:43 __init__.py
➜ cat /var/tmp/some_module/__init__.py
def foo():
print("From var/tmp Hello")
And you do:
➜ python
Python 3.7.10 (default, Oct 19 2021, 17:50:56)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.append("/tmp")
>>> sys.path.append("/var/tmp")
>>>
>>>
>>> import some_module
>>>
>>>
>>> some_module.foo()
Hello
Notice that python found the first system path (/tmp) where some_module was found.
Thus:
➜ python
Python 3.7.10 (default, Oct 19 2021, 17:50:56)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.append("/var/tmp")
>>> sys.path.append("/tmp")
>>> import some_module
>>>
>>> some_module.foo()
From var/tmp Hello

Empty variables when working with OS library

I tried multiple times to make this work without results, here's the code
import os, sys
try:
with open("syscore.lib", "r") as confFile:
readConfFile = confFile.readlines()
fileExist = True
except:
fileExist = False
if fileExist is True:
method = "r"
else:
method = "w"
for _ in range(2):
with open("syscore.lib", method) as confFile:
try:
readConfFile = confFile.readlines()
except:
confFile.write(os.system("python --version").replace("Python ", ""))
print(readConfFile)
The problem come again in a similar way down here
import os
test = [str(os.system('python --version'))]
test1 = os.system('python --version')
print('PV: '+str(test1))
print('Python Version: '+test[0])
Can anyone help me with this?
Thanks
As noted in the relevant thread here, os.system() returns the process exit value. 0 means success. If you want to capture the printed output, use os.popen() instead:
import os
python_version = os.popen("python -V").read().strip()
And the output is 'Python 3.6.6'.
Hope this helps.
if you only want to get python version then try,
Python 2.7.12 (default, Nov 12 2018, 14:36:49)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=12, releaselevel='final', serial=0)
>>> version = "{}.{}.{}".format(*sys.version_info)
'2.7.12'
>>>
you will get in python3,
Python 3.5.2 (default, Nov 12 2018, 13:43:14)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> "{}.{}.{}".format(*sys.version_info)
'3.5.2'
>>>
or you can use,
>>> import sys
>>> sys.version
'3.5.2 (default, Nov 12 2018, 13:43:14) \n[GCC 5.4.0 20160609]'
>>>

Is 'file' a keyword in python?

Is file a keyword in python?
I've seen some code using the keyword file just fine, while others have suggested not to use it and my editor is color coding it as a keyword.
No, file is not a keyword:
>>> import keyword
>>> keyword.iskeyword('file')
False
The name is not present in Python 3. In Python 2, file is a built-in:
>>> import __builtin__, sys
>>> hasattr(__builtin__, 'file')
True
>>> sys.version_info[:2]
(2, 7)
It can be seen as an alias for open(), but it was removed in Python 3, where the new io framework replaced it. Technically, it is the type of object returned by the Python 2 open() function.
file is neither a keyword nor a builtin in Python 3.
>>> import keyword
>>> 'file' in keyword.kwlist
False
>>> import builtins
>>> 'file' in dir(builtins)
False
file is also used as variable example from Python 3 doc.
with open('spam.txt', 'w') as file:
file.write('Spam and eggs!')
As others suggested, type in Python 3 it is not defined by default:
Python 3.8.10 (default, Nov 14 2022, 12:59:47)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'file' is not defined
The color coding in VS Code and possibly other editors probably refers to Python 2, where it is defined by default, it is the type returned by open():
Python 2.7.18 (default, Jul 1 2022, 12:27:04)
[GCC 9.4.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> file
<type 'file'>

Can't access https sites using urllib on python2.7

eduardo#camizao:/$ python2.7
Python 2.7.3 (default, Sep 26 2013, 20:03:06)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib
>>> url1 = 'http://www.google.com'
>>> url2 = 'https://www.google.com'
>>> f = urllib.urlopen(url1)
>>> f = urllib.urlopen(url2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/urllib.py", line 87, in urlopen
return opener.open(url)
File "/usr/lib/python2.7/urllib.py", line 211, in open
return getattr(self, name)(url)
File "/usr/lib/python2.7/urllib.py", line 355, in open_http
'got a bad status line', None)
IOError: ('http protocol error', 0, 'got a bad status line', None)
>>>
When I try to connect to an https site, using urllib I got error above.
Proxies are correctly setup. Debugging python code, I have noticed in urllib.py that an import on ssl library is not performed. So, https calls are also not performed. Can anyone help me, please? I do have to use urllib, instead of urllib2 or another one. Thanks in advance.
It's not something wrong with the way you are writing it at least:
$ python
Python 2.7.4 (default, Sep 26 2013, 03:20:26)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib
>>> url1 = 'http://www.google.com'
>>> url2 = 'https://www.google.com'
>>> f = urllib.urlopen(url1)
>>> f = urllib.urlopen(url2)
>>> f.read()[:15]
'<!doctype html>'
>>>
So that's what it's not. It must be something with your environment or your config then. You said you are using proxies?
EDIT:
I'm able to open it via an open proxy (won't include said proxy because who knows if it is sketchy - substitute with your own proxy:
$ python
Python 2.7.4 (default, Sep 26 2013, 03:20:26)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib2
>>> proxy_handler = urllib2.ProxyHandler({'http': 'http://some-sketchy-open-proxy'})
>>> opener = urllib2.build_opener(proxy_handler)
>>> opener.open('https://www.google.com')
<addinfourl at 140512985881056 whose fp = <socket._fileobject object at 0x7fcbba9b1ed0>>
>>> _.read()[:15]
'<!doctype html>'
>>>
Try it that way (note that I used urllib2, not urllib) with your own proxy URL. Hope that helps!
EDIT 2:
Using only urllib:
$ python
Python 2.7.4 (default, Sep 26 2013, 03:20:26)
[GCC 4.7.3] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> import urllib
>>> proxies = {'http': '189.112.3.87:3128'}
>>> url = 'https://www.google.com'
>>> filehandle = urllib.urlopen(url,proxies=proxies)
>>> filehandle.read()[:15]
'<!doctype html>'
>>>

Python ctype can't find dll?

Python ctype can't find AntTweakBar.dll ?? and the file dosn't exist for python OS file system call, but exists in the c:\Windows\System32 dir.
C:\Users\dkm>dir c:\Windows\System32\ant*dll
Volume in drive C is Windows 7
Volume Serial Number is FC61-5FBB
Directory of c:\Windows\System32
23/07/2012 12:05 AM 641,536 AntTweakBar.dll
22/07/2012 11:43 PM 774,144 AntTweakBar64.dll
2 File(s) 1,415,680 bytes
0 Dir(s) 47,418,232,832 bytes free
C:\Users\dkm>python
Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from ctypes.util import find_library
>>> import os
>>> print os.path.exists('C:\\Windows\\System32\\antweakbar.dll')
False
>>> find_library("AntTweakBar")
>>>
why can't ctype find the dll?
there are 2 t's in the file name
antweakbar.dll - name given by you
AntTweakBar.dll - actual file name
C:\\Windows\\System32\\antweakbar.dll
should be C:\\Windows\\System32\\anttweakbar.dll
for example (checking with inetcfg.dll, as i don't have anttweakbar.dll), see below for Python 2.7.2
In [136]: import os
In [137]: os.path.exists("C:\\Windows\\System32\\inetcfg.dll")
Out[137]: True

Categories

Resources