Using a python2 library with python3 - python

I'm using python3 and geolite2, but I'm finding that I cannot pass in the IP address that I want to look up and I get the following error. I have tried converting to utf-8 and encoding, but am getting the same error.
from geoip import geolite2
ip_address = request.access_route[0] or request.remote_addr
print(">>>", ip_address)
ip_bytes = ip_address.encode('utf-8')
loc = geolite2.lookup(ip_bytes)
or
loc = geolite2.lookup(ip_address.encode())
Following error:
TypeError: 'str' does not support the buffer interface
What format should the IP go in as. In the original doc, it is string.
http://pythonhosted.org/python-geoip/

I would suggest trying the official Python geoip2 API or python-geoip-yplan. The latter is a fork of python-geoip with better Python 3 support.

Related

Using pyobjc-framework-Quartz in Python 3

I've installed the library 'pyobjc-framework-Quartz'
pip install pyobjc-framework-Quartz
And in Python2, the following lines work perfectly:
provider = Quartz.CGDataProviderCreateWithFilename(input_file_path)
pdf = Quartz.CGPDFDocumentCreateWithProvider(provider)
But in Python3, I get the error message:
provider = Quartz.CGDataProviderCreateWithFilename(input_file_path)
ValueError: depythonifying 'char', got 'str' of 1
I've tried converting to char*
from ctypes import *
path = c_char_p(input_file_path)
but nothing seems to work. Can someone explain the error?
Thanks,
Ryan
I've worked it out. The problem is that the string input_file_path in python3 is a Unicode string, and needs to be converted to a binary string before use in objc APIs.
input_file_path_converted = input_file_path.encode('utf-8')
provider = Quartz.CGDataProviderCreateWithFilename(input_file_path_converted)
.
(Except that it only work for filenames with standard "ASCII" range alphanumerics...)

"_pickle.UnpicklingError: the STRING opcode argument must be quoted" in py2 to py3 ndarray transmission

I have a workstation running Python2 with a ROS environment which obtains a camera image from a robot and sends it over the network to a Python3 machine using the standard socket library. I can't seem to unpickle correctly the opencv ndarray image.
I am able to successfully transfer simple data as lists, but I encounter an error when trying to transfer an image.
On the Python2 system, I obtain my image in this way:
img = CvBridge().imgmsg_to_cv2(img_data, desired_encoding='bgr8') # Convert from ROS image to OpenCV image
Obtaining an ndarray.
I serialize it with:
data = pickle.dumps(img, protocol=0)
And I send it.
Back on the Python3 machine, I try to unpickle it using:
response = pickle.loads(data_in, encoding='latin1') # To read a Python2 dump
At this point, I obtain the following error:
_pickle.UnpicklingError: the STRING opcode argument must be quoted
The only other solutions that I have found address cases in which data had been transferred between Unix and Windows machines, which is not my case.
In vscode (on windows 10), you should open file that is showing this error and then change option CRLF to LF and then save the file then UnpicklingError: the STRING opcode argument must be quoted error will be disappeared.
An update on this topic, for possible future reference to whoever will experience the same problem.
The problem was not caused, as I initially thought, by a misconversion between Py2 and Py3 pickled byte stream. It was caused, instead, by the incorrect transmission of the data: I was interrupting the connection before all the packages had arrived.
This is the block of code that solved my problem:
data_in = b''
while True:
block = self.socket.recv(4096)
if block:
data_in += block

Python: piping pcap file to stdout gives error

I am trying to pipe the output of xz to a custom python script:
xz -cd file.pcap.xz | myscripy.py
However, I get an error when the script attempts to run this line:
#!/usr/bin/env python2.7
from __future__ import print_function
import pcap
import io
STDIN_ALIAS = '/proc/self/fd/0'
pcap.pcap(io.open(STDIN_ALIAS, 'r'))
and received an error
pcap.pcap(io.open(STDIN_ALIAS, 'r'))
File "pcap.pyx", line 196, in pcap.pcap.__init__
TypeError: expected string or Unicode object, _io.TextIOWrapper found
I am on Ubuntu 18.04 and running under python 2.7.
You can't use Python to pass in packets from a file to pcap.pcap(). The pypcap library you are using is a thin wrapper around the pcap_open_offline() and pcap_create() C functions, and offers no facilities for passing in a Python file object. This wrapper only accepts a filename or a network interface name, nothing else.
The pcap_open_offline() function does accept - as an alias for stdin, so just pass that in directly:
import pcap
sniffer = pcap.pcap('-')
The error message already tell you what happened. You need a string to the pcap() function, not a file object. To fix this, try
pcap.pcap(io.open(STDIN_ALIAS, 'r').read())
But I am not sure this will work as your file might be binary instead of text. In such case, you may want to open with 'rb' instead of 'r' flag, and do some conversion afterwards (especially if you use Python 3 instead of Python 2.7).
I see another issue: your code is not portable as it depends on this:
STDIN_ALIAS = '/proc/self/fd/0'
A pythonic way to read the stdin is the follows (see Reading binary data from stdin)
import sys
string = sys.stdin.read()
Have you tried upgrading PyPcap to work on Python 3? This could help, since Unicode handling is a lot cleaner and less prone to surprises on Python 3. The appropriate package is available, at least on Debian (and probably derived distros as well). Look for: python3-pypcap.

TypeError: 'str' does not support the buffer interface & configparser

I'm newbie here and I wouldn't want to ask such a easy question as my first post but I don't know anything about Python even I'm a PHP/C programmer.
I have a python script in Figway tools which is called RegisterDevice.py to register my own sensor hardware to FIWARE Lab. But some code lines of that script doesn't work as I expected because of Python3.4. This may not be my problem but I don't have too much time to wait an official solution that's why I thought that I could resolve it as a person who is familiar to the programming.
I've searched on the web for solution but I couldn't find any exact solution for it yet. As far as I read bytes and unicode strings are two different types in Python3.x but I couldn't realize where I have to encode or maybe decode string to other type on the code. Maybe I have to do something else...
Here is the part of script which gave me error like above.
# Load the configuration file
with open(CONFIG_FILE,'r+') as f:
sample_config = f.read()
#config = ConfigParser.RawConfigParser(allow_no_value=True)
config = configparser.RawConfigParser(allow_no_value=True)
config.readfp(io.BytesIO(sample_config))
Error:
Traceback (most recent call last):
File "RegisterDevice.py", line 47, in <module>
config.readfp(io.BytesIO(sample_config))
TypeError: 'str' does not support the buffer interface
Firstly readfp() is deprecated in Python3 and you should use read_file().
The best way is probably using the read() function directly when you want to work with a file. You should set encoding as the second parameter if you expect non-ASCII characters inside the file.
The alternative is to read_string() and give it a string directly.
I have been doing work very similar to this, and I believe this script runs, but you will have to verify if it gives you the desired results:
import configparser
with open('.coveragerc','r+') as f:
#config = ConfigParser.RawConfigParser(allow_no_value=True)
config = configparser.RawConfigParser(allow_no_value=True)
config.readfp(f)

jira-python invalid syntax

First time using jira-python, and I get this error when I run just a simple initialization.
from jira.client import JIRA
jira = JIRA()
Error:
File "C:\Python32\lib\site-packages\jira\resources.py", line 146
if re.search(u"^User '(.*)' was not found in the system\.", error, re.U):
SyntaxError: invalid syntax
Any ideas? I am running this with py32
It looks very much like a bug.
They are claiming python 3 support, but there are u strings in the source code. Python 3 doesn't support u strings, all of the strings are unicode.
Consider submitting an issue to the python-jira bug tracker.
I guess you already installed Jira in your CMD, like:
$ pip install jira
Then just try something like the following:
from jira import JIRA
jira = JIRA('https://jira.atlassian.com') #Project URL
issue = jira.issue('KEY-1')
print issue.fields.project.key # 'KEY'
print issue.fields.summary # 'Issue Summary'

Categories

Resources