python

Send keyboard event using subprocess

I have two python scripts. First one is just script waiting for user keyboard input. When user presses a key it print a pressed key value. Second script calls first one through subprocess using Popen like this p = Popen('python first_script.py', shell=True, universal_newlines=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT) print p.commun...

How to migrate from virtualenv to buildout?

I'm attempting to move a project from virtualenv to buildout, but I don't think I've grasped the whole concept of buildout. All the tutorials I've found discuss buildout in the context of using it with Zope, which I'm not using and therefore can't see how to continue. My file structure with virtualenv is as follows: myapp/ app.py W...

Flipping bits in python

Hello, Given an integer n , i want to toggle all bits in the binary representation of that number in the range say lower to upper. To do this i do the following [bit_string is a string containing 1's and 0's and is a binary representation of n] for i in range(lower,upper+1): n ^= (1 << len(bit_string)-1-i) #Toggle the ith bit Then...

Howto generate TrueLicence in Python

We have a licencing server which generates keys using the Java TrueLicense library. I would like to move that code to a Python using the same algorithm so that the new keys will be equivalent with keys generated with the Java code. Perhaps it is possible to use PyCrypto for this. Does anyone know if this can be done without too much effo...

Store python classes as pickles in GAE?

Hi, I am porting a Python investing application to Google App Engine. Every market that you can trade in is a plugin: for example the stocks trading and FOREX trading are all plugins. The application stores the portfolio (which is a Portfolio class instance containing the active investments (class instances) and history) as a pickle. H...

PyArg_ParseTuple and a callback function pointer

I have code like the following: PyObject *callback; PyObject *paths; // Process and convert arguments if (!PyArg_ParseTuple(args, "OO:schedule", &paths, &callback)) return NULL; What exactly happens inside PyArg_ParseTuple? My guess is that callback gets the function pointer I passed to args (also PyObject...

Country-based Super User Access

I'm looking to provide super-user access to entities belonging to a specific country. eg. Swedish SU can only admin Swedish entities, etc... However, I'm new to django (taking over an old system) and I need a lifeline. I'd like to be able to specify a relationship table. I've already added a userprofile and with that I have a new fi...

Test for email charsets with python

I want to import emails from an mbox format into a Django app. All database tables are Unicode. My problem: sometimes the wrong charset is given, sometimes none at all. What is the best way to deal with these encoding issues? So far, I merely nest exceptions to try the two most common charsets I receive mails in (utf-8 and iso-8859-1): ...

python: cannot concatenate 'str' and 'long' objects

I'm trying to set up a choice field in django, but I don't think this is a django issue. The choices field takes an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field. Here's my code: self.fields['question_' + question.id] = forms.ChoiceField( label=question.label, help_text=qu...

Python Regular Expression Match All 5 Digit Numbers but None Larger

I'm attempting to string match 5-digit coupon codes spread throughout a HTML web page. For example, 53232, 21032, 40021 etc... I can handle the simpler case of any string of 5 digits with [0-9]{5}, though this also matches 6, 7, 8... n digit numbers. Can someone please suggest how I would modify this regular expression to match only 5 d...

Python: How to download a zip file

I'm attempting to download a zip file using this code: o = urllib2.build_opener( urllib2.HTTPCookieProcessor() ) #login p = urllib.urlencode( { usernameField: usernameVal, passField: passVal } ) f = o.open(authUrl, p ) data = f.read() print data f.close() #download file f = o.open(remoteFileUrl) localFile = open(localFile, "wb") loca...

Do you use data mappers with MongoDB?

I've been diving into MongoDB with kind help of MongoKit and MongoEngine, but then I started thinking whether the data mappers are necessary here. Both mappers I mentioned enable one to do simple things without any effort. But is any effort required to do simple CRUD? It appears to me that in case of NoSQL the mappers just substitute one...

Python: How to extract required information from a string?

I am new to Python. Is there a StringTokenizer in Python? Can I do character by character scanning and copying. I have the following input string data = '123:Palo Alto, CA -> 456:Seattle, WA 789' I need to extract the two (city, state) fields from this string. Here is the code I wrote name_list = [] while i < len(data)): if li...

random.randint for non integer number? [Python]

How can I make a random number between something like 0.1 to 0.9 ? randint only work for integer numbers =/ Thank you ...

How to create an excel chart using py-appscript?

Hey! I am using Excel 2011 v14 and trying to dynamically create a chart based on the selected range on my worksheet. To select a range, I use the following code segment: xl = app('Microsoft Excel') tcell = 'B' qcell = 'C' for r in xrange(2, 16): xl.cells[tcell + str(r)].value.set(r) xl.cells[qcell + str(r)].value.set(random.ra...

Python efficiency of and vs multiple ifs

Is there an efficiency difference between using and in an if statement and using multiple if statements? In other words, is something like if expr1 == expr2 and expr3==expr4: dostuff() different from an efficiency standpoint then: if expr1 == expr2: if expr3 == expr4: dostuff() My very basic testing does not reveal a diffe...

gtk logic behind treeviewcolumns needing cell renderers

From what I understand about GTK, if I have a TreeView, I can't just use any widget I want to display information about a column. For text, you need a gtk.CellRendererText. For toggle buttons, a gtk.CellRendererToggle. For anything else, it seems you have to implement yourself, which, from a sample one for buttons that I saw, doesn't loo...

Parsing blockbased program output using Python

I am trying to parse the output of a statistical program (Mplus) using Python. The format of the output (example here) is structured in blocks, sub-blocks, columns, etc. where the whitespace and breaks are very important. Depending on the eg. options requested you get an addional (sub)block or column here or there. Approaching this us...

Python Web Crawlers and "getting" html source code

So my brother wanted me to write a web crawler in Python (self-taught) and I know C++, Java, and a bit of html. I'm using version 2.7 and reading the python library, but I have a few problems 1. httplib.HTTPConnection and request concept to me is new and I don't understand if it downloads an html script like cookie or an instance. If y...

Access to aliased functions in a Python module

I am consolidating many shell-like operations into a single module. I would then like to be able to do: pyscript.py: from shell import * basename("/path/to/file.ext") and the shell.py module contains: shell.py: import os.path.basename The problem is that functions imported to the shell module are not available, since the import st...