text
stringlengths
226
34.5k
Cython: Dynamically linking with a dll/so Question: I'm working with an API which is distributed as a dll/so file that I need to dynamically link with my python program. To accomplish this, I want to use Cython. I have been able to, in the past, link with the dll statically. This works well, except that the API comes ...
On keystroke insert line of code in (mac)vim, for pdb Question: I'm looking for the way to insert a line of code with a keystroke like `leader``p` in Macvim I want to insert the following line of code: import pdb; pdb.set_trace() Probably not an unheard of line of code in python land Answer: I'd...
How to access a database initialized in a class from another class in python? Question: How would I go about implementing the MainPage class? import cgi import os import logging from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.e...
Python: Regex and String Length in byte Question: I am writing a program in python and have some question (I am 100% new to python): import re rawData = '7I+8I-7I-9I-8I-' print len(rawData) rawData = re.sub("[0-9]I\+","",rawData) rawData = re.sub("[0-9]I\-","",rawData) ...
Python: Are `hash` values for built-in numeric types, strings standardised? Question: I came to this question while pondering about the ordering of `set`, `frozenset` and `dict`. Python doesn't guarantee any ordering, and any ordering is coupled to the `hash` value at some level. But is the hash value for a value of a ...
How to express a context free design grammar as an internal DSL in Python? Question: [Note: Rereading this before submitting, I realized this Q has become a bit of an epic. Thank you for indulging my long explanation of the reasoning behind this pursuit. I feel that, were I in a position to help another undertaking a s...
Getting the event name rather than integer ID in wxPython Question: I have the following code: `self.sliderR.Bind(wx.EVT_SCROLL,self.OnSlide)` In the function `OnSlide` I have the inserted the code `pdb.set_trace()` to help me debug. In the pdb prompt if I type `event.GetEventType()` it returns a number (10136) but ...
Django inlines working on Dev server, yet not on Apache Test server? Question: I'm having an issue where the Inline Admin functionality is behaving differently in different environments. In Dev, when editing a technology I get a link at the bottom to add more Roll Modifiers as needed that works flawlessly. In Test, I...
python fabric prompted for password everytime i execute a sudo command Question: Below is a small code I've been working on to install packages on the remote server. The code is working fine and the packages are being installed, but once the installation is complete I get prompted for entering the password. Any idea wh...
Python: Persistent cookie, generate `expires` field Question: I'm trying to generate the text for a persistent cookie in a simple Python web application. I'm having trouble finding a way to generate the `expires` field. The text format for the field is somewhat complicated, and I'd rather not write code to generate it...
Bcc Field in SMTP [ showing/not showing ] problem Question: I'm trying to use python's smtplib to send, via _gmail_ , an email with bcc addresses. I use this code: #imports etc... fromAddr = sender@origin.com to = [ recpt1@destinationTo.com ] cc = [ recpt2@destinationCc.com ] bcc = [ recp...
Clarification on why this C code works Question: I'm learning C today. I've been coding in managed languages (Java, C#, Python, etc.) for some time now. I thought I was understanding the details of pointers, but then I wrote the following code that worked as expected, but generated an 'incompatible pointer type' warnin...
Parse HTML using Python and Beautiful Soup Question: <div class="profile-row clearfix"><div class="profile-row-header">Member Since</div><div class="profile-information">January 2010</div></div> <div class="profile-row clearfix"><div class="profile-row-header">AIGA Chapter</div><div class="profile-information"...
Python: svndumpfilter2 and new line characters on Windows Question: When running svndumpfilter2 on Windows, I get a problem that seems to take its origin in the fact that the dump file has sometimes CRLF endings. Some files in the SVN database had CRLF line endings. But it seems that Python counts CRLF as one characte...
How to stitch several PDF pages into one big canvas-like PDF? Question: I have a 32-page PDF of my family tree. Instead of having the family tree all on one really big PDF page (which is what I want), it is formatted so a group of 8 individual US letter-sized pages are supposed to be stitched across the width; 4 rows o...
Building Boost 1.46.1 *with openmpi*? Question: I would like to build all of the [Boost](http://www.boost.org/) library on Ubuntu 11.04 with gcc 4.5.2. So I went about downloading the tar.bz2 file. I expanded it. I ran bootstrap.sh and noticed it complaining about unicode, so I installed: `sudo apt-get install libicu-...
Difference between pydoc and help()? Question: Are these two things different? The results that the two give in Python are similar. Answer: `help()` is a Python function. `pydoc` is a command-line interface to the same thing. If you want to see more what pydoc does, take a look in pydoc.py (`import pydoc; pydoc.__f...
In python, removing thousands comma from numbers in a list where the numbers are separated by commas Question: I have a list of data similar to that below: a = ['"105', '424"', '"102', '629"', '"104', '307"'] I want this data to be in a form similar to that of below: a = ['105424', '...
How to close urllib2 connection? Question: I have made a program using urllib2 that makes a lot of connections across the web. I noticed that eventually that this can be DDoS worthy; I would like to know how to close down each connection after I have done my business to prevent such an attack. The code I am using to o...
Python: Unbound method Question: When I try to bind a method, I get an error: Traceback (most recent call last): File "pygametest3.py", line 12, in <module> render = winback.rend() TypeError: unbound method rend() must be called with winback instance as first argument (got nothing inste...
Unit test terms Question: Colleagues of mine are calling a class with test methods a fixture, but I think that is wrong because a "fixture" is a fixed environment for testing. [NUnit uses the (wrong?) term "TestFixture"](http://www.nunit.org/index.php?p=testFixture&r=2.5) too. [Wikipedia](http://en.wikipedia.org/wiki...
Python 3.2 Unable to import urllib2 (ImportError: No module named urllib2) Question: I am using Windows, and I get the error: ImportError: No module named urllib2 I think [this](http://stackoverflow.com/questions/2532321/python-importerror- no-module-named-urllib) is the solution for Linux. But how...
What are equivalents to R's "phyper" function in Python? Question: In R, I use the `phyper` function to do a hypergeometric test for bioinformatics analysis. However I use a lot of Python code and using rpy2 here is quite slow. So, I started looking for alternatives. It seemed that `scipy.stats.hypergeom` had something...
how to open a new bash window from python and insert commands into the new bash window Question: I have been attempting, with little success, to open a terminal or konsole window from python and to insert commands into the terminal or konsole window. So far, I have the following: import os os.s...
Python Right Click Menu Using PyGTK Question: So I'm still fairly new to Python, and have been learning for a couple months, but one thing I'm trying to figure out is say you have a basic window... #!/usr/bin/env python import sys, os import pygtk, gtk, gobject class app: ...
python re module to replace the binary data inside a text file? Question: I know mixing text and binary is awful, but I have to do this. I want to replace the binary content, which is around with "Content-Type: image" and "----", by string "XXXXXXXX" So the code for test is: # coding=utf-8 import r...
Find offset between system-time and Internet time using Python Question: How would you find the time offset between the local OS system-time and Internet time from various Internet time sources using Python? Answer: Use [ntplib](http://pypi.python.org/pypi/ntplib/). Right from the manual: >>> import nt...
Ipython no readline available and pip install readline error Question: I installed ipython but it doesn't have the readline option. I first downloaded gnu readline and compiled and installed. DIdn't know whether it was a proper solution but was the first thing I thought of. It still wouldn't work to no avail with the s...
Python Pyramid - Add multiple chameleon base templates Question: I am using [this](http://docs.pylonsproject.org/projects/pyramid_cookbook/dev/templates.html#using- a-beforerender-event-to-expose-chameleon-base-template) procedure to use a base template which the other templates can derive from. How can I create multi...
Send XML using urllib Question: Following this [link](http://stackoverflow.com/questions/3020979/send-xml- file-to-http-using-python) I tried sending a XML file to my web service using GET: import urllib from createfile import XML URL = "http://http://localhost:8080/mywebservice ...
Android XML + Object Storage Question: I am sorry if this is a simple fix (I'm sure it probably is) but after a few hours of me and my friend google, I came up empty. I have an XML file that I have retrieved from a server (using httpclient for cookie handling goodness). I now wish to search through the XML. The XML de...
Update numbers in the middle of a string Question: I'm looking at diff-style output, but I need to update the line numbers. So I see: *** 1,2 ***** Actual line 1 Actual line 2 --- 1,2 ----- Expected line 1 Expected line 2 and in my results file, I'm at resline. So if resline=lin...
Python parse csv file - replace commas with colons Question: I suspect this is a common problem, but I counldn't seem to locate the answer. I am trying to remove all commas from a csv file and replace them with colons. I would normally use sed or vi for this, but I need to use a purely python implementation. Here is wh...
Strip Non alpha numeric characters from string in python but keeping special characters Question: I know similar questions were asked around here on StackOverflow. I tryed to adapt some of the approaches but I couldn't get anything to work, that fits my needs: Given a **python string** I want to strip every non alpha ...
Django/Jquery problem - Cannot assign "u'Agua'": "Venta.producto" must be a "Producto" instance Question: I'm using django+jquery autocomplete widget in my application. I customized the admin form of one of my tables to get autocomplete in the input textbox. It's working except that when I save the form the following e...
Can I have scripts outside my python exe? Question: I'm new to Python and starting to learn it. However I have one query, which I'd like to know for the future. Once I've made a python program and produced an exe via py2exe, is it then possible to execute python scripts outside of the exe or do I have to look at plugi...
An Efficient Lookup Table in redis--implemented using redis sets? Question: I want to use redis to store a large set of user_ids and with each of these ids, a "group id" to which that user was previously assigned: User_ID | Group_ID 1043 | 2 2403 | 1 The number of user_ids is fairly ...
Validating a zip file coming from stdin Question: After some frustration with `unzip(1L)`, I've been trying to create a script that will unzip and print out raw data from all of the files inside a zip archive that is coming from stdin. I currently have the following, which works: import sys, zipfile, Str...
python getoutput() equivalent in subprocess Question: I want to get the output from some shell commands like `ls` or `df` in a python script. I see that `commands.getoutput('ls')` is deprecated but `subprocess.call('ls')` will only get me the return code. I'll hope there is some simple solution. Answer: Use **subpro...
From HTML to CSS style with Python Question: I've extracted certain elements from a HTML page with beautifulsoup and want to extract the according CSS styles (which reside in most cases in external css files) via python. How can i get a jQuery selector if I have a HTML element? If i had this selector, i could use cssu...
Is a python script aware of its stored location path? Question: /home/bar/foo/test.py: I am trying `test.py` to print `/home/bar/foo` irrespective of from where I run the script from: import os def foo(): print os.getcwd() test run: [/home/bar $] python /home/bar...
How to make group permissions work in Django-nonrel for Google App Engine Question: I'm trying to get role-based permissions working for django-nonrel for GAE. Out of the box, it didn't seem to work, probably because of the implicit many- to-many relationship between Users and Groups, so I found and installed <http://...
How to fetch content of XML root element in Python? Question: I have an XML file, e.g.: <?xml version="1.0" encoding="UTF-8"?> <root> First line. <br/> Second line. </root> As an output I want to get: `'\nFirst line. <br/> Second line.\n'` I just want to notice, if the root element ...
List users in IRC channel using Twisted Python IRC framework Question: I am trying to write a function that will print the lists of nicks in an IRC channel to the channel using Twisted Python. How do I do this? I have read the API documentation and I have only seen one question similar to mine on this site, but it does...
Python Find & Replace Beautiful Soup Question: I am using Beautiful Soup to replace the occurrences of a pattern with a href link inside a HTML file I am facing a problem as described below modified_contents = re.sub("([^http://*/s]APP[a-z]{2}[0-9]{2})", "<a href=\"http://stack.com=\\1\">\\1</a>", str(s...
Why do rfind and find return the same values in Python 2.6.5? Question: I'm relatively new to Python, and something is acting up. Basically, when I call `str.rfind("test")` on a string, the output is the same as `str.find("test")`. It's best that I show you an example: Python 2.6.5 (r265:79063, May 6 20...
how do i dump a single sqlite3 table in python? Question: I would like to dump only one table but by the looks of it there is no parameter for this. I found this example of the dump but is is for all tables: # Convert file existing_db.db to SQL dump file dump.sql import sqlite3, os con = sq...
Python-LDAP simple_bind_s timeout Question: Is there a way to set timeout for "simple_bind_s" in python-LDAP manually? I have tested ldapObject.timeout = 10 it did not work for me. Any ideas? Thanks in advance.. Answer: Set the option `ldap.OPT_NETWORK_TIMEOUT` for the ldap object. import ldap ...
Problem running PyDev-developed apps in terminal Question: Im having some import problems with an application I developed in python with Eclipse/PyDev. Running the app from within Eclipse is no problem but when I try running it through the linux terminal the imports (which are imported from other folders (packages in E...
INSERT INTO SELECT syntax error Python ODBC with Microsoft Access Question: Had a long search through here and the web and can't seem to find any examples that explain why I am getting a syntax error on the following: import win32com.client ` PregCode = recordsetraw.Fields.Item("PregnancyCode...
Making a list of evenly spaced numbers in a certain range in python Question: What is a pythonic way of making list of arbitrary length containing evenly spaced numbers (not just whole integers) between given bounds? For instance: my_func(0,5,10) # ( lower_bound , upper_bound , length ) # [ 0, 0.5, 1...
issuing dos commands from inside ruby on rails controller in the same dos session Question: **Here is my scenario**. I have a ajax call in my web site to find the elevation at particular point. Once this point comes into an action of a controller in Ruby on rails, I have to use python on command line to find the elevat...
Circular reference between modules? Question: If have this module # mymodule.py import __main__ And I import it in the python interpreter: >>> import mymodule >>> dir(mymodule) ['__builtins__', '__doc__', '__file__', '__main__', '__name__', '__package__'] >>> dir() ...
How to animate a time-ordered sequence of matplotlib plots Question: I want to plot a sequence of .png images in matplotlib. The goal is to plot them rapidly to simulate the effect of a movie, but I have additional reasons for wanting to avoid actually creating an .avi file or saving matplotlib figures and then viewing...
Keep persistent variables in memory between runs of Python script Question: Is there any way of keeping a result variable in memory so I don't have to recalculate it each time I run the beginning of my script? I am doing a long (5-10 sec) series of the exact operations on a data set (which I am reading from disk) every...
How to change gif file to png file using python pil Question: this is my code : import Image,glob files = glob.glob("/small/*.gif") for imageFile in files: print "Processing: " + imageFile try: im = Image.open(imageFile) im.save( "/small_/", "png...
Why do I get an import error for multiprocessing when my code is called from a unittest? (PyCharm Python 3) Question: In one of my modules I do the following import: from multiprocessing import Pool This module works fine when called normally, but when I use this from a unittest, I get the followin...
Why do I see random read errors with Python BaseHTTPServer? Question: I have Python code that calls external HTTP services. I want to test this code by setting up mock HTTP servers that imitate those external services. I do this by starting a `BaseHTTPServer` in a separate thread, and then calling that server from the ...
Localization for scripts Question: I have a new piece of software I'm working on for my company that potentially will need some localization options for our plant in Mexico. As far as the application goes, C#/.NET has some great localization features that I will utilize. The new program will be making use of scripts th...
Can't input unicode in python IDE (Mac OS X) Question: I'm trying to collect some unicode raw_input in the default python IDE, and as far as I'm aware, it should be as simple as: >>> c = raw_input() 日本語 >>> print c 日本語 However, when I try to input the unicode characters, the computer be...
How to make Unix binary self-contained? Question: I have a Linux binary, without sources, that works on one machine, and I'd like to make a self-contained package that would run on a different machine of the same architecture. What is a way of achieving this? In my case, both machines have the same architecture, same ...
how to use python to produce a group of anagram with a given list Question: for example :giving a list ['car','bed','stop','pots','arc','tops','z','z','rac','deb'] then with the function: produce [['arc', 'car', 'rac'], ['bed', 'deb'], ['pots', 'stop', 'tops'], ['z', 'z']] A...
What's the common way to layout a Django app with Buildout/djangorecipe? Question: I have a Django app that I've set up using Buildout laid out like so: /workspace /bin /src /myproject settings.py /myapp views.py ... bootstrap.py ...
PyQt and QtDesigner Question: I am trying to implement a LED in PyQt named disLDR1 by trying to change the background color. I am trying to use QPalette to change the BackgroundRole. But what is the equivalent of Qt::red? Is this the correct way to set the background color or is there any other way? #!/...
error is raised when I try to remove elements (pydot objects) from a python list Question: I am writing an algorithm to represent regression trees, using pydot module (an interface to Graphviz's Dot language). In the algorithm, lists of Edges and Nodes are made, and then they are represented - that is working fine. Bu...
Fuzzy String Searching with Whoosh in Python Question: I've built up a large database of banks in MongoDB. I can easily take this information and create indexes with it in whoosh. For example I'd like to be able to match the bank names 'Eagle Bank & Trust Co of Missouri' and 'Eagle Bank and Trust Company of Missouri'. ...
Problems loading pygtk on Ubuntu 11.04 Question: I'm trying to use pygtk in Python but when I try running my code I get this error: Traceback (most recent call last): File "application.py", line 3, in <module> pygtk.require(2.0) File "/usr/lib/python2.7/dist-packages/pygtk.py", line 8...
from reportlab.platypus import ListFlowable, ListItem not working Question: I am a newbie to python. I have to create an ordered list in my pdf document using **Reportlab**. I found these two classes **ListFlowable(), ListItem()** in the [user-guide](http://www.reportlab.com/docs/reportlab-userguide.pdf) of Reportlab t...
SQLAlchemy (ORM, declarative): How to build query from key/values in a dict? Question: Using the [SQLAlchemy](http://www.sqlalchemy.org/) ORM (declarative form), how do you programatically create a query from a set of conditions in a dictionary? I wish to search for those records in a users table that match some crite...
Python XMl Parser with BeautifulSoup. How do I remove tags? Question: For a project I decided to make an app that helps people find friends on Twitter. I have been able to grab usernames from xml pages. So for example with my current code I can get `<uri>http://twitter.com/username</uri>` from an XML page, but I want ...
MiddleStorm middleware with bottle Question: How do you use [MiddleStorm](http://pypi.python.org/pypi/middlestorm) middleware with [bottle](http://bottlepy.org/)? I followed [this example](http://readthedocs.org/docs/bottle/en/latest/recipes.html), replacing SessionMiddleware with MiddleStorm, but I can't get it to wor...
Error when using ctypes module to acess a DLL written in C Question: I have a DLL with one single function That gets five doubles and one int: __declspec(dllexport) struct res ITERATE(double z_r,double z_i,double c_r, double c_i, int iterations, double limit) It retuns a custom struct caled res wh...
permutating on list Question: > **Possible Duplicate:** > [How to generate all permutations of a list in > Python](http://stackoverflow.com/questions/104420/how-to-generate-all- > permutations-of-a-list-in-python) I'm writing a function, called permutate(lst, acc) that permutes on the list of integers, finding its ...
Syntax Error When Running paster? Question: No idea what happened, but all of a sudden, paster stopped working on my server (working with virtualenv and pyramid). Tried reinstalling everything but didn't work - same error again: Traceback (most recent call last): File "bin/paster", line 7, in ? ...
Find pattern in xml string Question: I have following xml tags in my xml file as follows ''' `<pd:link scheme="http://www.w3.org/1999/xhtml" target="www.altruvest.org <pd:unicode ch="2014"/> or <pd:unicode ch="2014"/> www.Boardmatch.org">"www.altruvest.org <pd:unicode ch="2014"/> or <pd:unicode ch="2014"/> www.Boardma...
Link to Python with MinGW Question: I wan't want to create a cross-plattform programm that embedds the python interpreter, and compile it with MinGW. But the Python Binary distribution provides no libraries for MinGW to link with (only `python32.lib` for Visual C++), and the Python Source package provides no support fo...
Python random digit letter and additional generator Question: I would like to generate a random number string of N length with this code: import random import string N=512 print ''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for x in range(N)) ...
Help me with mercurial extension exportfiles Question: i'm trying to use [exportfiles](http://bitbucket.org/albert_brand/hgexportfiles/) extension for mercurial but I'm getting this error: c:\xampp\htdocs\dev>hg exportfiles -r 1 /tmp/export ** unknown exception encountered, please report by visiting ...
find and update duplicates in a list of lists Question: I am looking for a Pythonic way to solve the following problem. I have (what I think is) a working solution but it has complicated flow controls and just isn't "pretty". (Basically, a C++ solution) I have a list of lists. Each list contains multiple items of vary...
How do python submodules share a scarce resource between them? Question: I am breaking up a large monolothic python file into six separate submodules. Originally in onebigfile.py, I had conn = MySqldb.connect() c = conn.cursor() and then a function would use it as so: def getFro...
Associative Array does not work with eval() JavaScript Question: I am generating a data expressed as a Python dictionary which is dumped using simplejson via url which is in this format. {"2": "London", "3": "Tokyo", "4": "Sydney"} I am using `$.get` and storing into a variable data. However `eval(...
Mysql-python not installed with bitnami django stack? "Error loading MySQLdb module: No module named MySQLdb" Question: So I installed Bitnami Django stack, hoping as proclaimed 'ready-to-run' versions of python and mysql. However, I can't get python to syncdb: "Error loading MySQLdb module: No module named MySQLdb" I...
JSON to python dictionary: Printing values Question: Noob here. I have a large number of json files, each is a series of blog posts in a different language. The key-value pairs are meta data about the posts, e.g. "{'author':'John Smith', 'translator':'Jane Doe'}. What I want to do is convert it to a python dictionary, ...
Display a transparent .png in wxpython Question: I'm using Python 2.7. I need to display a .png image file in wxpython, such that the transparency is preserved, and you can still see the controls behind the transparent part of the image. This needs to work in Windows, Mac, AND Linux. Answer: I just wanted to add how ...
Python, import a modulo from a father directory Question: I want to know how import a file that is one level up. I read in google this: >>> sys.path.append("../") But I dont like it and i hope there are a better solution Answer: Another option, if what you are writing is part of a package, is to ...
python utf-8 problem Question: this is my script # -*- coding: utf-8 -*- from BeautifulSoup import BeautifulSoup import urllib2 res = urllib2.urlopen('http://tazeh.net') html = res.read() soup = BeautifulSoup(''.join(html)) title = soup.findAll('title') print ti...
Python PIL Image.tostring() Question: I'm new to Python and PIL. I am trying to follow code samples on how to load an image into to Python through PIL and then draw its pixels using openGL. Here are some line of the code: from Image import * im = open("gloves200.bmp") pBits = im.convert('RGBA')....
piping postgres COPY in python with psycopg2 Question: I'm writing a script to do a copy of some data between two machines on the same network using psycopg2. I'm replacing some old, ugly bash that does the copy with psql -c -h remote.host "COPY table TO STDOUT" | psql -c "COPY table FROM STDIN" Th...
Start up script for node.js repl Question: Is there a way configure node.js's repl? I want to require jquery and underscore automatically whenever the repl starts. Is there a file (noderc?) that node.js loads when it starts the repl? The equivalent in Python is to edit `~/.ipython/ipy_user_conf.py` with: ...
Is there a way to add multiple conditions in a for loop? Question: n=int(raw_input('enter the number of mcnuggets you want to buy : ')) #total number of mcnuggets you want yo buy for a in range(1,n) and b in range(1,n) and c in range(1,n) : if (6*a+9*b+20*c==n): ...
Reuse the same template for different content types Question: I'm creating quite a few Dexterity content types (thanks [zopeskel.dexterity](http://pypi.python.org/pypi/zopeskel.dexterity) devs!!) but even if I need them to be different content types (searches, collections...), some of them will be rendered equally. So...
What is a stack imbalance? Question: Having read this article [F# Versus Mathematics: Part One - Getting Started with BLAS and LAPACK](http://www.codeproject.com/KB/net- languages/FSharpvsmathematicspt01.aspx) I stumbled across the term `stack imbalance` in the paragraph `A Warning, Perhaps an Omen`. I [googled](http:...
Open Matlab file .mat with module PICKLE in Python Question: I want open a **Matlab** project with the module **Pickle** or **cPickle** in **Python language**. NOT with: from scipy.io import matlab mat=matlab.loadmat('file.mat') Can I use `pickle.load` with a .mat file? Answer: For some years...
Installing oursql on Mac OS Lion successes but import in python fails. **Why?** Question: I followed the installation instructions for installing oursql on Mac OS X. Since sudo pip install oursql told me, that it couldn't find `mysql_config` I (located it with `locate mysql_config` and) told it whe...
Opening a file in pwdir's folder in Python through Applescript Question: Opening a file available in present working directory's temp folder in python I tried pwdir=os.getcwd() tempdir=pwdir+"/temp/test.txt" f=open(tempdir,'r+') When I print the path of tempdir, it is showing up correctly ...
Find out time it took for a python script to complete execution Question: I have the following code in a python script: def fun() #Code here fun() I want to execute this script and also find out how much time it took to execute in minutes. How to find out how much time it took for th...
Python: replace a string by a float in txt file Question: Here is a problem. I have a .py file and a .txt. To simplify, my .txt looks like: @x@ In the .py I have x=15 I would like to replace @x@ in the txt by the value saved in the py, ie my txt should look like ...
Look for img and id tag, store URL in variable if both are true Question: I have been playing around with some Python now and start to get a hang of it. I have already came up with a project, but I can't work out some things. The purpose is to look inside a defined tag, such as the img tag or the a tag. If that's ...
using *args in struct.pack Question: I just read about the *args and **kwargs notation in python and decided to use it with my functions that use struct.pack as such: def pack_floats(*args): return struct.pack('%df' %len(args), args) But of course, it doesn't work because args is a tupl...
Python, check type of object after circular import Question: Here are two files, foo.py and bar.py bar.py has... from foo import * ...at the top. bar.py uses types defined n foo. When importing bar.py from foo I am having trouble determining the types of objects. Looking at the example below why d...