python 3 and the file object - python-3.x

I am looking at using setup.py to automatically generate python 3 code from python 2 sources using the 'use_2to3' attribute. My setup.py script includes the following statement:
VERSION = None
with file('version','rt') as FF:
VERSION = FF.read().lstrip().rstrip()
print("VERSION %s" % (VERSION) )
When I type 'python3 setup.py build' I get the error:
Traceback (most recent call last):
File "setup.py", line 18, in <module>
with file('version','rt') as FF:
NameError: name 'file' is not defined
which I understand is correct as the file object no longer exists and I should change it to 'open()'.
The concern is that the '2to3' utility does not detect this and leaves the code untouched.
I unfortunately use this idiom throughout my code.
Is this a bug in '2to3' ?

Use the open instead of the file.
It was tempting to use the file() instead of the open() in Python 2.x -- especially for those with OO background. The file() call resembled calling a constructor for creation of a file object. However, it was always recommended to use open() function instead. This may be the reason why 2to3 does not solve the case.
In Python 3, the file is unknown. The file objects are of the _io.TextIOWrapper class:
>>> f = open('a.txt', 'w')
>>> type(f)
<class '_io.TextIOWrapper'>
>>> f.__class__.__name__
'TextIOWrapper'

Related

Unittest: filename with point not loaded properly

Setup: PyCharm, Python 3.10
We have the naming convention to name our python unittest files like an URL. For example: my.domain.org.py
In the past, this was no issue. Now after an IDE and Python Update it does not run anymore. Selecting right click -> Run "Python tests in my.domain.org.py" throws the error:
Traceback (most recent call last):
File "D:\programs\Python\3.10.2\lib\unittest\loader.py", line 154, in loadTestsFromName
module = __import__(module_name)
ModuleNotFoundError: No module named 'my'
It seems, the loader is interpreting the "." in the filename as path.
How can I run the unittest without renaming the file (which solves the issue)?
you cannot import python files with invalid names (in your case has dots in it) directly, but there's a turn around, you can use the imp library like (here in the example I have a function named print_smth that prints "it works!" in the my.file.py):
import imp
with open('my.file.py', 'rb') as fp:
my_file = imp.load_module(
'my_file', fp, 'my.file.py',
('.py', 'rb', imp.PY_SOURCE)
)
if __name__ == "__main__":
my_file.print_smth()
output:
test.py:1: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
import imp
it works!
P.S: preferably DO NOT DO THAT! it is highly deprecated!

H5py Driver Issue on Qiskit Nature Drivers

While using the IBM Quantum experience, whenever I want to install any driver an error with the h5py appears.
Specifically, the error is
"Using default_file_mode other than 'r' is no longer supported. Pass
the mode to h5py.File() instead."
Does anyone have any solutions to it (not sure which version to revert back to). Thanks!!
You will need to add more details about your question. I could not replicate your error based on the information you provided. This is what I did:
First, I installed Qiskit Nature with this command pip install qiskit[nature].
Next, I entered the following Python commands:
>>> from qiskit_nature.drivers.second_quantization import HDF5Driver
>>> h5f = HDF5Driver()
>>> h5f
<qiskit_nature.drivers.second_quantization.hdf5d.hdf5driver.HDF5Driver object at 0x7fa28320a820>
>>> h5f.run()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/qiskit_nature/drivers/second_quantization/hdf5d/hdf5driver.py", line 63, in run
raise LookupError(f"HDF5 file not found: {hdf5_file}")
LookupError: HDF5 file not found: molecule.hdf5
There is no error when I imported the HDF5Driver module from the qiskit_nature package. An error occurs when I enter h5f.run(). This is expected, because I don't have a file named molecule.hdf5 (the default filename). If you have a different filename, modify commands above to use h5f = HDF5Driver("your_filename").
Tests run with Python 3.8.12 and qiskit_nature 0.3.0 running on Ubuntu Linux 5.11.0-1023-gcp.

Helper-command not working after importing NLTK

I discovered the phenomenon that always I enter the command
from nltk import *
the help command is not working anymore. I get the following error message then:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
Does anybody has an explanation for that phenomenon?
I am writing code in Visual Studio in Python 3.
Thanks and best wishes,
Marcus
Firstly, importing * from nltk is a bad idea. You pollute your namespace with many variables that are unknown/unclear to you.
$ python
# Native Python variables.
>>> vars()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}
>>> len(vars())
4
# After importing from *
>>> from nltk import *
>>> len(vars())
510
Next in Python, modules are not callable but functions are.
From https://docs.python.org/3/tutorial/modules.html
If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. Therefore, if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input instead. This is known as creating a script. As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you’ve written in several programs without copying its definition into each program.
To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable name.
Looking at the nltk.help module:
>>> from nltk import help
>>> type(help)
<type 'module'>
# A module is not callable.
>>> help()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
# A module contains definitions and statements.
>>> dir(help)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '_format_tagset', '_print_entries', 'brown_tagset', 'claws5_tagset', 'load', 'print_function', 're', 'upenn_tagset', 'wrap']
# A function is callable.
>>> type(help.brown_tagset)
<type 'function'>
>>> help.brown_tagset()
(: opening parenthesis
(
): closing parenthesis
)
*: negator
not n't
,: comma
,
--: dash
yada yada
Not directly related, but if your plan is to import all of nltk, just use import nltk. No need for the *
Looking at the nltk.help module, you would need to use one of the functions defined there. As nltk.help itself is not a function but a library location.
See: https://www.nltk.org/api/nltk.html?highlight=help#module-nltk.help
So if that is the module you want to use, try:
import nltk
nltk.help.upenn_tagset()

How to convert HTML to PDF with python3

How to convert HTML to PDF with python3? i write some code about webView with pyqt5,and i want to convert the html in the webView to pdf,what should i do?
i have tried to use the html2pdf,but it seem to only support python2.x
and i have tried to install the wkhtmltox-0.12.2.2_msvc2013-win64.exe and pdfkit,and then use the example code.
import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')
pdfkit.from_file('test.html', 'out.pdf')
pdfkit.from_string('Hello!', 'out.pdf')
but i also failed.and the error is following.
Traceback (most recent call last):
File "E:\Python34\lib\site-packages\pdfkit\configuration.py", line 21, in __init__
with open(self.wkhtmltopdf) as f:
FileNotFoundError: [Errno 2] No such file or directory: b''
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
pdfkit.from_url('http://google.com', 'out.pdf')
File "E:\Python34\lib\site-packages\pdfkit\api.py", line 22, in from_url
configuration=configuration)
File "E:\Python34\lib\site-packages\pdfkit\pdfkit.py", line 38, in __init__
self.configuration = (Configuration() if configuration is None
File "E:\Python34\lib\site-packages\pdfkit\configuration.py", line 27, in __init__
'https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf' % self.wkhtmltopdf)
OSError: No wkhtmltopdf executable found: "b''"
If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf
but i also failed.so what should i do? My system is window7 x64 ,python's version is 3.4
Since this hasn't had an accepted answer yet, there is a great library that works in Python 3 that I found after much searching and failed attempts at using PyPDF2, wkhtmltopdf beta branch for Python 3, qpdf, etc. It is weasyprint. I have the related answer and sample code here.
For completeness sake, from the documentation:
from weasyprint import HTML
HTML('http://weasyprint.org/').write_pdf('/tmp/weasyprint-website.pdf')
and it really works that easy.
'set path' probably means add **.exe to the system environment variable $Path$. For example, add D:\Program Files\wkhtmltopdf\bin to $Path$.

Problems using ambhas package: statistics module has no cpdf attribute

I am trying to use the ambhas package for copulas and the method
foo.generate_xy()
is not working.
This is error I get:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
generate()
File "C:/Users/Mypc/Desktop/sfsdf.py", line 19, in genera
x1,y1 = foo.generate_xy()
File "C:\Python33\lib\site-packages\ambhas\copula.py", line 179, in generate_xy
self._inverse_cdf()
File "C:\Python33\lib\site-packages\ambhas\copula.py", line 256, in _inverse_cdf
x2, x1 = st.cpdf(self.X, kernel = 'Epanechnikov', n = 100)
AttributeError: 'module' object has no attribute 'cpdf'
Basically I checked the code in the ambhas module and it turns out it is trying to use a method from the statistics module (imported as st), st.cpdf() which I do not have in my statistics module.
How can I fix this problem?
Here is an example of the code working. This is the very same code I am trying to run through the generate() function:
https://code.google.com/p/ambhas/wiki/Cookbook
The AMBHAS code depends on this statistics module, not the "official" one that is now included in Python 3.4. Unfortunately, the module doesn't appear to have been updated in a while, and the latest Windows installer is for Python 3.2, so you'll need to build it from source. You can do this with Cygwin, or by installing Visual C++ 2010 Express (here is a blog post describing the process, but I haven't tried it myself so I don't know if it's completely accurate - YMMV).
Once you've compiled the extension, make sure you remove the statistics module you installed previously before running python setup.py install.

Resources