text
stringlengths
226
34.5k
is it possible not to use "self" in a class? Question: > **Possible Duplicate:** > [Python: How to avoid explicit > 'self'?](http://stackoverflow.com/questions/1984104/python-how-to-avoid- > explicit-self) In python class if I need to reference the class member variable, I need to have a self. before it. This is an...
Synchronizing embedded Python in multi-threaded program Question: Here is the example of using Python interpreter in multi-threaded program: #include <python.h> #include <boost/thread.hpp> void f(const char* code) { static volatile auto counter = 0; for(; counter < 20; ++...
Python reading a tabbed text file into a series of lists Question: Hi as an inexperieced python user I would appreciate any help with the following programming challenge: I have a text file with tabulated data, I want to read it and put the values on each line into different python lists. The file looks like this: ...
Encoding problems in python x64 Question: i´m trying to write a little script for writting a sqlite table from an archive list saved in a file. the code so far is this: import os import _sqlite3 import sys print sys.path[0] mydir = sys.path[0] print (mydir) def listdir(mydir): lis=[] ...
Bootstrapping a web server in Scala Question: The following is possible using Python: $ apt-get install python $ easy_install Flask $ cat > hello.py from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ =...
Is `extend` faster than `+=`? Question: In python, we can concatenate lists in two ways: 1. lst.extend(another_lst) 2. lst += another_lst I thought `extend` would be faster than using `+=`, because it reuses the list instead of creating a new one using the other two. But when I test it out with `timeit`, it turn...
How to copy a message from one imap server to another imap server using Python imaplib? Question: I want to copy a message from one IMAP server to another IMAP server. I don't want to alter any of the message data. I'm using python imaplib. This is the code I tried: typ, data = connection1.uid('FETCH', ...
Capture single picture with opencv Question: I have seen several things about capturing frames from a webcam stream using python and opencv, But how do you capture only one picture at a specified resolution with python and opencv? Answer: Use SetCaptureProperty : import cv capture = cv.CaptureFromC...
Best way to store a python time.struct_time in a mysql database Question: I am using python's feedparser module, to parse an RSS feed. Once parsed, feedparser returns dates in a python 9 tuple time format (time.struct_time). I am want to store these values in my mysql database so I can later check the [Last-Modified h...
Formatting data quantity/capacity as string Question: A common task in many programs is converting a byte count (such as from a drive capacity or file size), into a more human readable form. Consider 150000000000 bytes as being more readable as "150 GB", or "139.7 GiB". Are there any libraries that contain functionali...
Python module visiable only in iPython Question: I have used `set PYTHONPATH=%PYTHONPATH%;dictionary_containing_modules` to make some modules globaly visiable. I have a script importing the modules with `import my_module`. When i run the script from the iPython shell (`run my_script.py`), i get no errors and the scri...
How do I use a relative path in a Python module when the CWD has changed? Question: I have a Python module which uses some resources in a subdirectory of the module directory. After searching around on stack overflow and finding related answers, I managed to direct the module to the resources by using something like ...
Python+ubuntu error Question: Am trying to run the following python program import re regex=re.compile("http...imgs.xkcd.com.comics.[\\S]*.[jpg|png]") f=open('out.txt') for a in f: print regex.findall(a) print '\n' when I type the code into the interpreter manually, it w...
Connecting and Saving Data With Redis Inside Celery Task Question: I have an object that saves data to Redis. It needs to block as less as possible, so I've decided to use Celery to offload the task. When I try to .save() the object outside of celery, it connects to Redis and stores the data just fine. However, when I ...
Abuse yield to avoid condition in loop Question: I need to search for the first, last, any, or all occurence of something in something else. To avoid repeating myself ([DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself)) I came up with the following solution. Of interest are the methods `search_revisions()` a...
wxReactor Problem Question: I am developing a program that uses Twisted and wxReactor. Everytime I try to exit the application, it hangs, and I have to force quit it. My wxPython OnClose() event does call reactor.stop(), which to my knowledge should fix this issue. In my quest for an answer, I've come across this ticke...
Ttk on python 2.7 Question: I just installed python 2.7 from the python website, and was surprised to find that ttk wasn't included. Did I make a mistake installing, or is ttk really not included in the standard release? Anyway, where can I get a copy of ttk to install in my python instalation. Note: I also heard that...
How to fix Python error importing ElementTree? Question: I'm beginning to learn python and here I'm trying to read from an xml file using ElementTree: import sys from elementtree.ElementTree import ElementTree doc = ElementTree(file="test.xml") doc.write(sys.stdout) However I get...
Use WTForms with webapp and Django templates on Google App Engine Question: I'm trying to use WTForms with webapp without much luck. I would like to be able to use the `form_field` templatetag, as shown in the documentation: `{% form_field form.username class="big_text" onclick="do_something()" %}` I've got WTForms ...
How do I use xml namespaces with find/findall in lxml? Question: I'm trying to parse content in an OpenOffice ODS spreadsheet. The ods format is essentially just a zipfile with a number of documents. The content of the spreadsheet is stored in 'content.xml'. import zipfile from lxml import etree ...
lxml build on Solaris 10 Question: Please can you help and advise with a problem with python 2.6.6 and lxml Solaris 10 build? Installation instructions: www.sunfreeware.com/download.html direct link to the file: <http://www.sunfreeware.com/ftp/pub/freeware/sparc/10/lxml-2.2.8-sol10-sparc- local.gz> [ra...
How to force Jinja2 templates to recompile? Question: I'm trying to switch Jinja2 template in the django app without restarting the application. Has anyone done this? Basically I need to force jinja2 to reload the templates once the skin selection change is applied. I've tried to re-create cache object on the templat...
ImportError: cannot import name tz (psycopg2) Question: I am using Windows XP, and using Python run time from <http://www.python.org/ftp/python/2.7/python-2.7.msi> If I am running in standalone application, `import psycopg2` doesn't cause me any trouble. However, when come to mod_wsgi + apache, I will get the followin...
How to bind engine when I want, when using declarative_base in SQLAlchemy? Question: Here's my code: from sqlalchemy import create_engine, Column, Integer from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker database_url = 'mysql://some_path' ...
Python CMS to create a video site like youtube? Question: Is anyone aware of a open source CMS written in python using which I can make a site like YouTube? Answer: [Django](http://www.djangoproject.com/) is a good Python Framework, as well as [CherryPy](http://www.cherrypy.org/) and [Pylons](http://pylonshq.com/). H...
Web Proxy to Simulate Network Problems Question: I need a way to simulate connectivity problems in an automated test suite, on Linux, and preferably from Python. Some sort of proxy that I can put in front of the web server that can hang or drop connections after one trigger or another (after X bytes transferred, etc) w...
How do I find mime-type in Python Question: I am trying out some CGI-scripting in Python. If a request come to my python script, how do I find the mime-type of the filetype? UPDATE: Adding more info Some images for now, adderess/image.jpg. But if I understand mime-type is part of the headers that the web-browsers send...
How to insert a string(Fri Nov 19 16:23:54 +0800 2010) into a table field whose type is TIMESTAMP? Question: I'm using Python and MYSQLdb to connect to Mysql. and now i need to insert a string "Fri Nov 19 16:23:54 +0800 2010" into a field, how can i do? Answer: You can parse that sting with Python `time.strptime()` m...
Prevent python shelve corruption Question: How should I prevent corruption in a shelve file? Should the shelve be closed most of the time and then opened only when I need to read or edit a value? Answer: If safety of your persistent objects is of high importance in your project, using `shelve` is not a good idea. Nei...
using stored variables as regex patterns Question: is there a way for python to use values stored in variables as patterns in regex? supposing i have two variables: begin_tag = '<%marker>' end_tag = '<%marker/>' doc = '<html> something here <%marker> and here and here <%marker/> and more he...
need fix Tkinter Error Question: I have my windows Wtere this AttributeError: 'NoneType' object has no attribute 'tk' ??? from Tkinter import * root = Tk() root.minsize(428, 285) root.maxsize(428, 285) root.resizable(width=NO, height=NO) root.title("TEST") root.wm_iconbitmap...
How to call Python functions dynamically Question: I have this code: fields = ['name','email'] def clean_name(): pass def clean_email(): pass How can I call `clean_name()` and `clean_email()` dynamically? For example: for field in fields: cl...
how do i insert inputs to find value of integrals in python? Question: I am working a physics coursework, and I am currently stuck at this section. I've trying but I couldn't get it right. Really need help here. Its about the trapezium rule, Question: What is the value of the integral in equation f(x)=x4*(1-x)44/(1+x^...
I want to write a tool without usage entry barriers. Do I have to write it in C? Question: I want to write an open-source tool for use by developers. I want to eliminate entry barriers, so if they like the idea, they just get the tool and start playing with it. In particular, I don't want an "Oh, should I also install...
Switching from amara to lxml in Python Question: I am trying to accomplish with lxml library something like this: <http://www.xml.com/pub/a/2005/01/19/amara.html> from amara import binderytools container = binderytools.bind_file('labels.xml') for l in container.labels.label: print l....
Testing Google App Engine app from terminal (python cli) Question: I'm running `from appname import model`, which gives me: ImportError: No module named google.appengine.api So I add the following Python path (the only path I could `find`): `PYTHONPATH=/Applications/GoogleAppEngineLauncher.app/Con...
shutil.move -> WindowsError: [Error32] The process cannot access the file Question: I use Python 2.5. and have a problem with shutil.move print(srcFile) print(dstFile) shutil.move(srcFile, dstFile) Output: c:\docume~1\aaa\locals~1\temp\3\tmpnw-sgp D:\dirtest\d\c\test.txt ...
Module uncallable? Unsure how to fix Question: I am just beginning with python and I've run in to an error I don't know how to fix. Please see the code examples below. I run `event_timer.py` and I get the following error message. Both of the files listed below are in the same folder. Traceback (most rece...
Screen Scraping in Python Question: I am currently trying to screen scrape a website to put info into a dictionary. I am using urllib2 and BeautifulSoup. I cannot figure out how to parse the web pages source info to get what I want and to read it into a dictionary. The info I want is displayed as `<title>Nov 24 | 8:00A...
How to write PIL image filter for plain pgm format? Question: How can I write a filter for python imaging library for pgm plain ascii format (P2). Problem here is that basic PIL filter assumes constant number of bytes per pixel. My goal is to open feep.pgm with Image.open(). See <http://netpbm.sourceforge.net/doc/pgm....
Creating a .zip archive with Python in MS DOS Question: I am new to programming. I am trying to learn Python using CH Swaroop's "Byte of Python". One example is to create a program which will backup some files from one directory to another and compress them into a .zip format. Unfortunately the example he gives is only...
How can I use Python to get the system hostname? Question: I'm writing a chat program for a local network. I would like be able to identify computers and get the user-set computer name with Python. Answer: Use [`socket`](http://docs.python.org/library/socket.html) and its [`gethostname()`](http://docs.python.org/libr...
Accessing static java methods in Python through jython Question: I am currently trying to access a static class in java, within python. I import as normal, then I try to get the class instance of the java class. from com.exmaple.util import Foo Foo. __class___.run_static_method() This does...
Executable path to Mac App Question: In a py2app/Mac Application Bundle, is there a way to spawn another instance of same app from within the app, by passing different command line arguments? or given a mac app bundle, how can I run it from command line and pass some arguments too? Edit1:forking is a limited option, ...
Insert javascript at top of including file in Jinja 2 Question: In Jinja2, I would like the following to work as it looks like it should, by running: from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader('.')) template = env.get_template('x.html') print te...
How to add custom parameters to an URL query string with Python? Question: I need to add custom parameters to an URL query string using Python Example: This is the URL that the browser is fetching (GET): /scr.cgi?q=1&ln=0 then some python commands are executed, and as a result I need to set follow...
Help building a mac application from python using py2app? Question: I have a Tkinter app written in python, and I want to make "native" (easy to run) mac and windows executables of it. I've successfully built a windows .exe using py2exe, but the equivalent process with py2app isn't working. Here's my setup.py: ` ...
Reliably force Return-Path with Python Question: I'm a Python junior, so keep that in mind. In a Python script, I need to set a Return-Path address that is different than the sender's address. (I'm using Gmail as SMTP server.) I've done lots of searching on this question and found plenty of "answers", but no solutions...
Getting macports django and python to work together Question: I'm a webdeveloper and I have a django project that I need to work on. I am running mac OSX 10.6.5 on a macbook pro. I used macports to install django and python 2.6. I now have some sort of problem, possibly related to my PATH / PYTHONPATH that prevents m...
RTMP: check if stream is online with Python Question: I have several Flash streams and I want to display only active/live/online streams. Can someone provide sample code that can check status of stream? or point out where I can grab it (I think Red5 and RTMPy should have this, but I completely don't have any experience...
Scrape Facebook in Python Question: I'm interested in getting the number of friends each of my friends on Facebook has. Apparently the official Facebook API does not allow getting the friends of friends, so I need to get around this (somehwhat sensible) limitation somehow. I tried the following: import s...
Python - Way to encode foreign characters in format Python can work with? Question: I'm working with large files in French and German. Basically, writing strings of characters from one file to another, collecting data from them, and so forth. Unfortunately, I have no idea what to import in order to let Python handle th...
Is it possible to reset locale to the portable locale? Question: According to the Python documentation: > "a program which has not called `setlocale(LC_ALL, '')` runs using the > portable 'C' locale. After having set the locale with `setlocale(LC_ALL, '')` is it possible to reset the locale back to the "portable" sta...
How does Python keep track of modules installed with eggs? Question: If I have a module, `foo`, in `Lib/site-packages`, I can just `import foo` and it will work. However, when I install stuff from eggs, I get something like `blah-4.0.1-py2.7-win32.egg` as a folder, with the module contents inside, yet I still only need...
Math question regarding Python's uuid4 Question: I'm not great with statistical mathematics, etc. I've been wondering, if I use the following: import uuid unique_str = str(uuid.uuid4()) double_str = ''.join([str(uuid.uuid4()), str(uuid.uuid4())]) Is `double_str` string squared as unique as ...
mod_wsgi WSGI script for non-frameworked Python web development Question: Most guides I saw for creating the WSGI file for use with mod_wsgi either sets it up for Django or Pylons. However, I would like to create the wsgi file without setting it up for any particular framework. How do I do this. The following is a code...
Single precision big endian float values to Python's float (double precision, big endian) Question: I need to receive hex encoded single precision big endian float values coming from an Arduino over a serial line (RS-232). How do convert them to Python's float which are big endians with double precision? The Arduino s...
How can I send a JSON object from a Python script to jQuery? Question: I've looked through APIs and all sorts of resources, but I can't seem to get the hang of fetching a JSON object from a Python script using AJAX. I'm sure the issue is with how I'm dealing with the JSON object. First, in a python script on my server...
SqlSoup relate() for many-to-many relation throwing exception Question: I'm using the following code to use SqlSoup with an existing database. import sqlalchemy from sqlalchemy.ext.sqlsoup import SqlSoup from sqlalchemy.orm import backref engine = sqlalchemy.create_engine('postgresql:///...
Removing control characters from a string in python Question: I currently have the following code def removeControlCharacters(line): i = 0 for c in line: if (c < chr(32)): line = line[:i - 1] + line[i+1:] i += 1 return line This is...
Serious instability with pygtk 2.22 and python 2.6 Question: Has anybody come across this? I've taken the GTK [HelloWorld sample](http://www.pygtk.org/pygtk2tutorial/examples/helloworld.py). It runs fine. However, if i `import win32ui`, then it does not shutdown properly (as explained in [this question](http://stackov...
Is there anyway to give a Zookeeper node a NULL ACL via python-bindings? Question: I'm trying to create a node using the python bindings that are bundled with the zookeeper distribution ( src/contrib/zkpython/ ). Using zookeeper-3.3.1. The pydoc for create states that if the ACL is NULL then that node will inherit its...
Realtime data processing in Django/Python Question: We are working on a project involving realtime data processing. We plan to use Django/Python. The actual process is: 1. Tens of thousands of devices take 4 samples per seconds (0, 0.25, 0.5, 0.75) and continuously send back to our Django server, basically they are ...
windows virtualenv using global packages Question: I have the latest versions of virtualenv,django-nonrel, djangotoolbox and django_mongodb_engine. The virtualenv was created with -no-site-packages. I attempted to follow the [quick start](http://django-mongodb- engine.github.com/mongodb-engine/) but I see the followin...
Which abbreviations should we use for python variable names? Question: In generally I'm using the standard naming stated in PEP-8 for variables. Like: delete_projects connect_server However sometimes I can't find any good name and the name just extend to a long one: project_name_...
Python3.1 - Open Opera Question: I have no idea why this won't work....I'm trying to open opera but it says cannot find runnable browser. op = webbrowser.get('C:\\Program Files\\Opera\\opera.exe') op.open_new_tab('http://www.stackoverflow.com') op.open_new_tab('http://www.stackoverflow.com')...
Jython: Import Modules From Other Sources (DB for instance)? Question: I'm using a Java program to load and run Jython scripts - using the org.python.util.PythonInterpreter. I'm storing the Jython scripts in a database : currently I'm having to extract the Python scripts to a file system prior to running them - to ens...
Last.fm api invalid method Question: I am trying to write a python script to do a query to Last.fm, but I keep getting an invalid method error returned. I don't want links to pre-written last.fm python libraries, I am trying to do this as a "test what I know" kind of project. Thanks in advance! import u...
Asynchronous getNext errors out when going out of table Question: I am using one of the examples for `GetNext` operation for an SNMPWalk of the tree. I am using the asynchronous variant to collect the OIDs - # GETNEXT Command Generator from pysnmp.entity.rfc3413.oneliner import cmdgen from pysnmp...
question about pexpect in python Question: I tried both pexpect and subprocess.Popen from python to call an external long term background process (this process use socket to communicate with external applications), with following details. 1. subprocess.Popen(launchcmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, ...
Which Python async library would be best suited for my code? Asyncore? Twisted? Question: I have a program I'm working on that will be reading from two 'network sources' simultaneously. I wanted to try out an asynchronous approach rather than use threading. This has lead me to wonder which library to use... I've come ...
SCons in Python Question: I would like to load SCons in an interactive Python session and enter directives that way as opposed to through an SConstruct or SConscript file. Is this possible? I'm trying to embed SCons functionality into another Python application. Answer: It would appear so, > Just add Scons to your P...
C++ | Progresssion Path Question: Inspired by the Question on [Python-Progression Path](http://stackoverflow.com/questions/2573135/python-progression-path-from- apprentice-to-guru) \- I know the `basic OOP-related topics`, `RTTI, Templates`. Reverting back from `Java' Collection Framework`, I tried to find such collec...
How do I set up a local python library directory / PYTHONPATH? Question: In the process of trying to write a Python script that uses PIL today, I discovered I don't seem have it on my local machine (OS X 10.5.8, default 2.5 Python install). So I run: easy_install --prefix=/usr/local/python/ pil an...
Can PyQt4 and Qt4/C++ co-exist peacefully on Windows? Question: I had previously installed PyQt4 on my Windows XP machine and was successful in getting everything to run. This evening, I downloaded the full Qt4 SDK (open source version) and installed it as well. After adding the path to the bin directory to my system e...
Python logging datagram handler Question: I am having a problem getting the example code shown in the python docs for the logging DatagramHandler, the code shown below gives EOFError exceptions on every datagram received. import socket import logging import cPickle import struct import sy...
How to maintain different version of a python module? Question: I have this core python module we use in our facility called mfxLib. I need to be able to keep different version of this module without breaking all the other modules/plugin that are importing this module. My solution was keep a duplicate of my module by ...
Python decorator for Django views: Check for a particular setting in UserProfile Question: I'd like to write a decorator to use on views all over my site to first check if the logged in user's UserProfile has a particular setting. In my case it's user.get_profile.user_status and the value could be either "expired" or "...
Key to OpenGL. Java / Scala / Python Question: one topic that has always been of highest interest to me is 3D Programming. I've made several attempts at programming small games and never really successed. After experiences with DirectX and C++, XNA and C#, as well as Unity3d and C#, I would like to try OpenGL. Just be...
How to find recurring patterns on a hexdump? Question: I need to find recurring patterns from an hexdump output. Every line in my output file is something like: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 Where `00` is a byte in hexadecimal. The patterns aren't of fixed length but they always ...
python, dynamically implement a class onthefly Question: this is related to [python, dynamically implement a class onthefly](http://stackoverflow.com/questions/4387847/python-dynamically- implement-a-class-onthefly). when i restarted my pc, couldnt get back to add comments to the post - below is an example to explain ...
Convert commented out print statements to logging calls - Python Question: I'm hacking on a framwork right now, and I'd like to use logging. However, the developers of the framework have been using print statements to debug, and they are all commented out for the production release. I was wondering, does anyone know of...
How can I change the extension name in a string with bash? Question: I want to translate the following python code to bash. The code changes the extension name to .html and runs Safari to open it. #!/usr/bin/env python import os.path import os oldName = $TM_FILEPATH (name, ext) = os....
Making HTTP HEAD request with urllib2 from Python 2 Question: I'm trying to do a HEAD request of a page using Python 2. I am trying import misc_urllib2 ..... opender = urllib2.build_opener([misc_urllib2.MyHTTPRedirectHandler(), misc_urllib2.HeadRequest()]) with `misc_urllib2.py` containing...
Running shell commands from bytes objects in python 3.1 (Or writing UTF-8 mp3 tags in python 3.1) Question: I'm writing a script which uses .CUE files to split monolithic music files into individual tracks, then encodes them in MP3 along with correct tags from the CUE. It's all working, but unfortunately the tags (appl...
Error importing module _md5, and relevant RPM Question: I have a python script that used to run, although since moving servers at work it now throws up a strange error: >>> import _md5 ImportError: No module named _md5 The general setup is all correct, as is my python path and seemingly eve...
Python Automated Web Page downloading, with Username, Password and Cookies Question: I'm trying to implement in Python a simple program that reads rom web pages and writes them to files. There are about 2000 pages of messages incrementally numbered, but some numbers are missing. The Web site is username and password p...
Create and parse multipart HTTP requests in Python Question: I'm trying to write some python code which can create multipart mime http requests in the client, and then appropriately interpret then on the server. I have, I think, partially succeeded on the client end with this: from email.mime.multipart i...
Apache mod_python with django issue Question: While running a django application on top of apache2 mod_python, I am getting this error message in my apache error log. [Tue Dec 14 14:26:45 2010] [error] [client SOME_IP] IOError: Write failed, client closed connection., referer: http://example.com/ Tra...
Is it possible to import a 3D model into pyglet? Question: Me and a friend are working on an openGL game written in python, using the pyglet library. Now we finished the map drawing code, and have come to a point where we need to import some models that will be displayed on the map. Pyglet doesn't seem to support it, a...
Python solve equation for one variable Question: I'm trying to solve an equation in python using SymPy. I have a generated equation (something like `function = y(8.0-(y**3.0))` which I use with SymPy to create a new equation like this: `eq = sympy.Eq(function, 2)` which outputs `y(8.0-(y**3.0)) == 2`. but `sympy.solve(...
Python (newbie) Parse XML from API call Question: I've look for some tutorials/other questions on stack/documentation and still can't figure it out. ugh!!! Making the API request and the parsing out (want to assign to variables but that's a bonus to this question), This is what I'm trying. Why can't I list the title a...
how to optimally count elements in a python list Question: This is almost the same question than [**here**](http://stackoverflow.com/questions/3710976/counting-unique- elements-in-a-list), except that I am asking about the most efficient solution for a sorted result. I have a list (about 10 integers randomly between 0...
Linear Interpolation. How to implement this algorithm in C ? (Python version is given) Question: There exists one very good linear interpolation method. It performs linear interpolation requiring **at most one multiply per output sample**. I found its description in a third edition of Understanding DSP by Lyons. This m...
What does Python return when instantiating new classes? Question: I'm finding loads of quirks with Python when instantiating a new class. I'm sure it's just because I'm not used to the language, but even so, the behaviour I can see is really strange. If I open up iPython and type the following: class Pe...
Mixed lexicographic and numeric sorting Question: I have a list such as: ## input.txt foo.bar.1 foo.bar.2 foo.bar.3.x.y.z foo.bar.10 foo.bar.0 baz.10.qux baz.3.qux that needed to be sorted. I need to treat this as a dot separated fields, where numeric fields are needed to b...
python: shuffle characters in string to get all possible string combinations Question: just looking for a script in Python which receives some string and returns all possible strings made up of all the possible combinations of the chars in the original string... I've found scripts to shuffle randomly the chars in a st...
How to convert regexp to python from perl Question: in Perl: if ($test =~ /^id\:(.*)$/ ) { print $1; } Answer: In Python: import re test = 'id:foo' match = re.search(r'^id:(.*)$', test) if match: print match.group(1) In Python...
Why does "c.execute(...)" break the loop? Question: I am trying to change some data in an sqlite3 file and I my non-existing knowledge in python and google-fu made me end up with this code: #!/usr/bin/python # Filename : hello.py from sqlite3 import * conn = connect('database') ...
Python BeautifulSoup equivalent to lxml make_links_absolute Question: So lxml has a very hand feature: make_links_absolute: doc = lxml.html.fromstring(some_html_page) doc.make_links_absolute(url_for_some_html_page) and all the links in doc are absolute now. Is there an easy equivalent in Beauti...