GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing pythonadventures.wordpress.com — python3 – Python Adventures Python AdventuresWelcome to the Jungle!
Archive
Posts Tagged ‘python3’
JiVE: A general purpose, cross-platform image viewer with some built-in NSFW support, written in Python 3.6 using PyQt5In the past 2-3 weeks I’ve been working on a general purpose, cross-platform image viewer that has some built-in NSFW support. It’s called JiVE and it’s in Python 3.6 using PyQt5. A unique feature of JiVE is that it allows you to browse online images just as if they were local images. You can find it on GitHub: https://github.com/jabbalaci/JiVE-Image-Viewer. I also wrote a detailed documentation. Screenshots In action:
Selecting an NSFW subreddit:
Read the docs for more info.
Categories: python, Qt
Tags: cross-platform, image viewer, PyQt5, python3
creating a Python 3 virt. env. on UbuntuProblem $ virtualenv -p python3 venv
Running virtualenv with interpreter /usr/bin/python3
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 8, in
import base64
File "/usr/lib/python3.4/base64.py", line 9, in
import re
File "/usr/lib/python3.4/re.py", line 324, in
import copyreg
File "/usr/local/lib/python2.7/dist-packages/copyreg.py", line 3, in
from copy_reg import *
ImportError: No module named 'copy_reg'
Error in sys.excepthook:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 53, in apport_excepthook
if not enabled():
File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 24, in enabled
import re
File "/usr/lib/python3.4/re.py", line 324, in
import copyreg
File "/usr/local/lib/python2.7/dist-packages/copyreg.py", line 3, in
from copy_reg import *
ImportError: No module named 'copy_reg'
Original exception was:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 8, in
import base64
File "/usr/lib/python3.4/base64.py", line 9, in
import re
File "/usr/lib/python3.4/re.py", line 324, in
import copyreg
File "/usr/local/lib/python2.7/dist-packages/copyreg.py", line 3, in
from copy_reg import *
ImportError: No module named 'copy_reg'
Awesome! :( Solution python3 -c 'import sys; del sys.argv[0]; s = sys.argv[0]; exec(open(s).read(), {"__file__": s, "__name__": "__main__"})' `which virtualenv` -p python3 venv
Life on Arch / Manjaro is easier. There Python 3 has been the default for years.
Categories: python
Tags: arch, manjaro, python3, ubuntu, virtualenv, workaround
pyvenv: create virtual environmets for Python 3.4+For creating virtual environmets, I’ve used I like to store my virtual environments in a dedicated folder, separated from the project directory. virtualenvwrapper, by default, stores the virt. env.’s in the pyvenv pyvenv ~/.virtualenvs/flasky_project It will create a Python 3 virt. env. virtualenv / virtualenvwrapper # blog post: http://goo.gl/oEdtT3 # virtualenvwrapper for Python 3 or Python 2 mkvirtualenv -p `which python3` myenv3 mkvirtualenv -p `which python2` myenv2 # virtualenv for Python 3 or Python 2 virtualenv -p python3 myproject3 virtualenv -p python2 myproject2 # When the env. is created, activate it # and launch the command python within. # Verify if it's the correct version. TL; DR
Categories: python
Tags: python3, pyvenv, virtual environment, virtualenv, virtualenvwrapper
XML to dict / XML to JSONProblem Well, if you have a dict, you can convert it to JSON with “ Solution import xmltodict
# It doesn't work with Python 3! Read on for the solution!
def convert(xml_file, xml_attribs=True):
with open(xml_file) as f:
d = xmltodict.parse(f, xml_attribs=xml_attribs)
return d
This worked well under Python 2.7 but I got an error under Python 3. I checked the project’s documentation and it claimed to be Python 3 compatible. What the hell? The error message was this: Traceback (most recent call last):
File "/home/jabba/Dropbox/python/lib/jabbapylib2/apps/xmltodict.py", line 247, in parse
parser.ParseFile(xml_input)
TypeError: read() did not return a bytes object (type=str)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./xml2json.py", line 27, in <module>
print(convert(sys.argv[1]))
File "./xml2json.py", line 17, in convert
d = xmltodict.parse(f, xml_attribs=xml_attribs)
File "/home/jabba/Dropbox/python/lib/jabbapylib2/apps/xmltodict.py", line 249, in parse
parser.Parse(xml_input, True)
TypeError: '_io.TextIOWrapper' does not support the buffer interface
I even filed an issue ticket :) After some debugging I found a hint here: you need to open the XML file in binary mode! XML to dict (Python 2 & 3) import xmltodict
def convert(xml_file, xml_attribs=True):
with open(xml_file, "rb") as f: # notice the "rb" mode
d = xmltodict.parse(f, xml_attribs=xml_attribs)
return d
XML to JSON (Python 2 & 3) import json
import xmltodict
def convert(xml_file, xml_attribs=True):
with open(xml_file, "rb") as f: # notice the "rb" mode
d = xmltodict.parse(f, xml_attribs=xml_attribs)
return json.dumps(d, indent=4)
make a script run under Python 2.x and 3.x tooProblem Anyway, Manjaro switched to Python 3.x, that’s the default, thus “python” points to Python 3. I use Ubuntu on my other machines where Python 2 is the default. I would like to modify my scripts (at least some of them) to run on both systems. For instance, in Python 2.x you call “raw_input”, while this function was renamed to “input” in Python 3.x. Solution from __future__ import (absolute_import, division,
print_function, unicode_literals)
It ensures a nice transition from Python 2 to Python 3. To solve the “raw_input” problem, you can add these lines: import sys
if sys.version_info >= (3, 0):
raw_input = input
You can continue using “raw_input”, but if it’s executed with Python 3.x, “raw_input” will point to the “input” function. Of course, the ideal solution would be to switch to Python 3, but I’m not ready for that yet :) Update (20141228) from six.moves import input Then — just like in Python 3 — call the function “input()” to read from the standard input. For more info. read the official docs.
Categories: python
Tags: input, python3, raw_input, transition
make bpython use Python 3Problem How could I have another Solution In a previous post I showed how to patch $ cd $ mkdir bpython_python3 $ cd bpython_python3 $ mkvirtualenv bpython_python3 # creates a Python 3 virt. env. (bpython_python3)$ pip install bpython (bpython_python3)$ which bpython /home/jabba/.virtualenvs/bpython_python3/bin/bpython # sample; will be different in your case (bpython_python3)$ deactivate $ I suggest adding the following aliases to your alias bpy='bpython' alias bpy3='/home/jabba/.virtualenvs/bpython_python3/bin/bpython' Of course, you need to customize the path for Now “ [django] virtualenvwrapper with Python 3Problem For my Django projects I use virtualenvwrapper to manage my virtual environments, so the first question was: how to create a Python 3 virt. env. with virtualenvwrapper? Well, maybe my installation got corrupted somehow, but I ran into this problem: $ mkvirtualenv -p `which python3` tmpenv
Running virtualenv with interpreter /usr/bin/python3
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 8, in <module>
import base64
File "/usr/lib/python3.4/base64.py", line 9, in <module>
import re
File "/usr/lib/python3.4/re.py", line 324, in <module>
import copyreg
File "/usr/local/lib/python2.7/dist-packages/copyreg.py", line 3, in <module>
from copy_reg import *
ImportError: No module named 'copy_reg'
Error in sys.excepthook:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 53, in apport_excepthook
if not enabled():
File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 24, in enabled
import re
File "/usr/lib/python3.4/re.py", line 324, in <module>
import copyreg
File "/usr/local/lib/python2.7/dist-packages/copyreg.py", line 3, in <module>
from copy_reg import *
ImportError: No module named 'copy_reg'
Original exception was:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 8, in <module>
import base64
File "/usr/lib/python3.4/base64.py", line 9, in <module>
import re
File "/usr/lib/python3.4/re.py", line 324, in <module>
import copyreg
File "/usr/local/lib/python2.7/dist-packages/copyreg.py", line 3, in <module>
from copy_reg import *
ImportError: No module named 'copy_reg'
Solution First, install pip3: sudo apt-get install python3-pip sudo pip3 install virtualenvwrapper Then, add the following lines to your .bashrc: export WORKON_HOME=$HOME/.virtualenvs export PROJECT_HOME=$HOME/workspace # customize if needed export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv source /usr/local/bin/virtualenvwrapper.sh Try if it works for you. In my case, I had to edit the file “ #!/usr/bin/env python3 The consequence of changing the first line was that creating Python 3 environments became the default, but at least it works now. Create a Python 3 virt. env.: mktmpenv Create a Python 2 virt. env.: mktmpenv -p `which python2` If you use the command “
Categories: django, python
Tags: django 1.7, pip3, python3, virtualenv, virtualenvwrapper
get the command pip3Problem Solution #1 (20140912) sudo apt-get install python3-pip Solution #2 Steps: $ wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py $ sudo python3 get-pip.py Now you have a “ Generating pseudo random text using Markov chainsThe following entry is based on this post: Generating pseudo random text with Markov chains using Python (by Shabda Raaj). Problem Solution The algorithm for generating pseudo random text is the following:
When reading and splitting up a corpus to words, don’t remove commas, punctuations, etc. This way you can get a more realistic text. Example A is the father of B. C is the father of A. From this we can build the following dictionary: {('A', 'is'): ['the'],
('B.', 'C'): ['is'],
('C', 'is'): ['the'],
('father', 'of'): ['B.', 'A.'],
('is', 'the'): ['father', 'father'],
('of', 'B.'): ['C'],
('the', 'father'): ['of', 'of']}
The key is a tuple of two consecutive words. The value is a list of words that follow the two words in the key in the corpus. The value is a multiset, i.e. duplications are allowed. This way, if a word appears several times after the key, it will be selected with a higher probability. Let’s start the generated sentence with “ Python code #!/usr/bin/env python3
# encoding: utf-8
import sys
from pprint import pprint
from random import choice
EOS = ['.', '?', '!']
def build_dict(words):
"""
Build a dictionary from the words.
(word1, word2) => [w1, w2, ...] # key: tuple; value: list
"""
d = {}
for i, word in enumerate(words):
try:
first, second, third = words[i], words[i+1], words[i+2]
except IndexError:
break
key = (first, second)
if key not in d:
d[key] = []
#
d[key].append(third)
return d
def generate_sentence(d):
li = [key for key in d.keys() if key[0][0].isupper()]
key = choice(li)
li = []
first, second = key
li.append(first)
li.append(second)
while True:
try:
third = choice(d[key])
except KeyError:
break
li.append(third)
if third[-1] in EOS:
break
# else
key = (second, third)
first, second = key
return ' '.join(li)
def main():
fname = sys.argv[1]
with open(fname, "rt", encoding="utf-8") as f:
text = f.read()
words = text.split()
d = build_dict(words)
pprint(d)
print()
sent = generate_sentence(d)
print(sent)
if sent in text:
print('# existing sentence :(')
####################
if __name__ == "__main__":
if len(sys.argv) == 1:
print("Error: provide an input corpus file.")
sys.exit(1)
# else
main()
Tips In our version the current state consists of two words. If you decide to put more words (3 for instance) in the current state, then the text will look less random, but also, it will look less gibberish (see also this gist). Links
Categories: python
Tags: Markov, python3, random text, text generator
Blog Stats
Random PostRecent Postsascii
bash
beautifulsoup
book
bpython
challenge
command-line
convert
cron
crontab
date
datetime
distance
dropbox
email
eric
exercise
extract
file
firefox
github
google
hacking
heroku
html
ide
imdb
imgur
install
ipython
java
jinja2
json
linux
module
modules
MongoDB
movies
news
pdf
perl
pi
pip
print
pylint
pypi
python3
python shell
quote
readline
reddit
redirect
refactoring
regexp
requests
reverse
review
shell
sound
stdout
string
tab
text
threads
time
tip
tutorial
unicode
url
video
virtualenv
virtual environment
virtualenvwrapper
xml
zip Archives
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Cookie Policy
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |