text
stringlengths
226
34.5k
Issue including std::vector to cython Question: I have a problem importing the vector class to cython using from libcpp.vector cimport vector when I add this and try to compile the pyx file I get python setup.py build_ext --inplace running build_ext skipping 'kmc_cy.c' Cython extension (up-to-date) building 'kmc_cy' extension gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -fmessage-length=0 -O2 -Wall -D_FORTIFY_SOURCE=2 -fstack-protector -funwind-tables -fasynchronous-unwind-tables -g -fPIC -I/usr/include/python2.7 -c kmc_cy.c -o build/temp.linux-x86_64-2.7/kmc_cy.o kmc_cy.c:254:18: fatal error: vector: No such file or directory compilation terminated. error: command 'gcc' failed with exit status 1 Here is my setup.py from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import sys sys.path.append("/usr/lib64/python2.7/site-packages/Cython/Includes/libcpp") ext_modules = [Extension("kmc_cy", ["kmc_cy.pyx"])] setup( name = 'kmc_cy', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules, ) Cheers Answer: As `std::vector` is C++ code, you need to set the correct language: ext_modules = [Extension("kmc_cy", ["kmc_cy.pyx"],language='c++')] Then `g++` should be used instead of `gcc` and the file name should end with `.cpp` or `.cc`. See [this answer](http://stackoverflow.com/questions/2105508/wrap-c-lib-with-cython) for more details.
How can I send a Python program (including libraries) to a friend? Question: I want to send a program that I made to my friend, but the problem is it's not going to work on his computer, because he doesn't have all the libraries installed. For example : #! /usr/bin/env python2.7 from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * from bs4 import BeautifulSoup as bs import sys how can I send him all necessary libraries? hope my question is clear. Answer: You could also try "Python to EXE": http://www.py2exe.org/ This packs up a script & it components into an package that runs with an included exe. If you are brave, you can "roll your own", gathering up the key DLL's and EXE for python: .\MSVCR71.dll .\OCI.dll .\python.exe .\python25.dll And all the needed *.pyc & *.pyd files in Python HOME's Lib directory: .\Lib\cx_Oracle.pyc .\Lib\cx_Oracle.pyd .\Lib\encodings\aliases.pyc .\Lib\glob.pyc .\Lib\logging\config.pyc .\Lib\os.pyc .\Lib\pprint.pyc ... excreta ... Taking all the files and any of your developed *.py scripts and rolling them up into an appropriate directory structure and zipping it up for distribution.
Reference Before Assignment Error Question: > **Possible Duplicate:** > [referenced before assignment error in > python](http://stackoverflow.com/questions/855493/referenced-before- > assignment-error-in-python) So I've started to try to teach myself a little Python, and I've come up against my first error already. When I try to increment 'guesses' (I want to be able to display how many guesses it's taken) in the else statement I get a reference before assignment error, which I don't understand, as I've assigned 'guesses' a value before the start of the function. Here's my code - import random def guessFunc(): guess = input("Guess a number between 1 and 10: \n") guess = int(guess) if guess == num: print("Congratulations, you got it right") else: guesses += 1 guessFunc() num = random.randint(1,10) guesses = 1 guessFunc() What confuses me more is that fact that if I put print(guesses) into the start of my function it will print the value I've assigned 'guesses'. I really just don't get how the function can see the value and can print it, but can't change it. If anyone could expalin to me why this happens, I'd be really grateful, I 'm guessing it's a local/global thing but I'm really not sure. Answer: Python scoping allows values from outer scopes to fall into scope for reading. So you can access and use a global from a function as you describe with the `print()` statement. However, when you want to assign, you need to use the `global` statement to tell Python you want to assign to a global, not a local value, meaning that if you do `global guesses` before you try to assign to it, it will work. As you don't here, it will see the assignment and therefore presume you want to create a local variable, but as you are doing `+=` it needs the existing value of the new local variable, which of course doesn't exist, causing an error. Do note that globals are considered bad practice in general and are best avoided as they make it very hard to see what a function is going to do. It is far better to make the function return a value and work with that. A better way to do what you want would be something like this: import random def guessFunc(): guesses = 0 while guess != num: guess = input("Guess a number between 1 and 10: \n") guess = int(guess) guesses += 1 print("Congratulations, you got it right") return guesses num = random.randint(1,10) guesses = guessFunc() Firstly we use a `while` loop to repeat the action, as recursion is not optimized in Python, then we return the number of guesses performed from the function, and assign it to `guesses` rather than using globals.
Getting User in django-socketio Question: Once a message is sent through a Socket.IO connection from client (JS) to server (django/python) using django-socketio, is it possible to figure out which user was authenticated when the page was rendered? In this case the view is being served up by django and it requires authentication -- normally on the server I would be able to do `user = request.user`, but in the `events.py` file the `request.user` just returns an `AnonymousUser` object. This makes sense because the websocket server is an entirely separate process than the django web server, and thus the user has not authenticated on that socket connection. I'm thinking I'll have to come up with some clever code to embed the user ID into the message that is being sent to the server, and in that case I would need to add some handshaking to ensure that the end user cannot spoof it. Has anyone come up with a clever solution to this problem? Answer: Found my own solution to this issue. The trick is to add the `session_key` from the django `request` object into the django-socketio message before you send it up to the server; then back on the server-side you can resolve the `session_key` back to a User object. Here is the code: **Template file:** (served up by django server) <input type="hidden" id="session_key" value="{{ request.session.session_key }}"> ... <script type="text/javascript" charset="utf-8"> function someHandler(action, post_id, some_val){ var data = { 'action': action, 'post_id': post_id, 'value': some_val, 'session_key': $("#session_key").val() }; socket.send(data); } </script> **events.py:** (processed by django-socketio server) from django.contrib.sessions.models import Session from django.contrib.auth.models import User def message(request, socket, context, message): session = Session.objects.get(session_key=message['session_key']) uid = session.get_decoded().get('_auth_user_id') user = User.objects.get(pk=uid) _Profit!_
Make pivot tables in sql like in spss Question: I have lots of data in PostgreSQL. But I need to do some pivot tables like it does SPSS. For example i have table with cities and states. create table cities ( city integer, state integer ); insert into cities(city,state) values (1,1); insert into cities(city,state) values (2,2); insert into cities(city,state) values (3,1); insert into cities(city,state) values (4,1); Actually in this table i have 4 cities and 2 states. I want to do pivot table with percentage like city\state |state-1| state-2| city1 |33% |0% | city2 |0% |100% | city3 |33% |0% | city4 |33% |0% | totalCount |3 |1 | I understant how do to this in this particulary case with sql. But all i want is to cross one variable by another (just count distinct values and devide it by "count(*) where variable_in_column_names=1 and so on) using some stored function. Im looking now at plpython.Some my questions are: 1. How to output set of records with not having temporary table with shape that fits number and type of output columns. 2. Maybe there is working solutions? As i can see, input will be table name, column name of first variable, column name of second variable. Doing lots of queries in function's body (count(*),loop thru every distinct value in variables and count it and so on) and then return a table with percentage. 1. Actually i dont have a lot of rows in one query(about 10k), and may be the best way to do such things in raw python,not plpython? Answer: You might want to give [pandas](http://pandas.pydata.org) a try, which is an excellent python data analysis library. To query a PostgreSQL database: import psycopg2 import pandas as pd from pandas.io.sql import frame_query conn_string = "host='localhost' dbname='mydb' user='postgres' password='password'" conn = psycopg2.connect(conn_string) df = frame_query('select * from cities', con=conn) Where `df` is a [DataFrame](http://pandas.pydata.org/pandas- docs/stable/dsintro.html#dataframe) like: city state 0 1 1 1 2 2 2 3 1 3 4 1 You can then create a pivot table using `pivot_table` and dividing by the total to get percentages: totals = df.groupby('state').size() pivot = pd.pivot_table(df, rows='city', cols='state', aggfunc=len, fill_value=0) / totals Giving you the result: state 1 2 city 1 0.333333 0 2 0 1 3 0.333333 0 4 0.333333 0 Finally to get the layout you want, you just need to rename the index and columns, and append the totals: totals_frame = pd.DataFrame(totals).T totals_frame.index = ['totalCount'] pivot.index = ['city%i' % item for item in pivot.index] final_result = pivot.append(totals_frame) final_result.columns = ['state-%i' % item for item in final_result.columns] Giving you: state-1 state-2 city1 0.333333 0 city2 0.000000 1 city3 0.333333 0 city4 0.333333 0 totalCount 3.000000 1
Python - How to end function in a way that ends thread (i.e. decrease threading.activeCount() by 1)? Question: I've just starting experimenting with threading as a way to download multiple files at once. My implementation uses thread.start_new_thread(). I want to download 10 files at a time, then wait for all 10 files to finish downloading before starting the next 10 files. In my code below, threading.activeCount() never decreases, even when download() ends with exit(), sys.exit() or return. My workaround was to introduce the downloadsRemaining counter, but now the number of active threads continually increases. At the end of the sample program below, there will be 500 active threads, where I really only want 10 at a time. import urllib import thread import threading import sys def download(source, destination): global threadlock, downloadsRemaining audioSource = urllib.urlopen(source) output = open(destination, "wb") output.write(audioSource.read()) audioSource.close() output.close() threadlock.acquire() downloadsRemaining = downloadsRemaining - 1 threadlock.release() #exit() #sys.exit() None of these 3 commands decreases threading.activeCount() #return for i in range(50): downloadsRemaining = 10 threadlock = thread.allocate_lock() for j in range(10): thread.start_new_thread(download, (sourceList[i][j], destinationList[i][j])) #while threading.activeCount() > 0: <<<I really want to use this line rather than the next while downloadsRemaining > 0: print "NUMBER ACTIVE THREADS: " + str(threading.activeCount()) time.sleep(1) Answer: According to [the documentation](http://docs.python.org/2/library/thread.html#thread.start_new_thread): > Start a new thread and return its identifier. The thread executes the > function function with the argument list args (which must be a tuple). The > optional kwargs argument specifies a dictionary of keyword arguments. **When > the function returns, the thread silently exits.** When the function > terminates with an unhandled exception, a stack trace is printed and then > the thread exits (but other threads continue to run). (Emphasis added.) So the thread should exit when the function returns.
Using grequests to send a pool of requests, how can I get the response time of each individual request? Question: I am using the grequests python library to send GET requests asynchronously to our server. I cant figure out how to get the server response time for each individual request within the pool of requests being sent out? unsentrequests=(grequests.get(u) for u in self.urls) # make a pool of requests responses=grequests.map(unsentrequests) # send the requests asynchronously To get the start time of a request-response pair I could do the following: grequests.get(u,headers={'start':time.time()) print responses[0].request.headers['start_time'] But how can I grap the time that the response was received at? Answer: `grequests`, like `requests`, support an `hook` keyword argument where you can assign a function that does something with the response object: def do_something(response): print response.status_code unsentrequests=(grequests.get(u, hooks = {'response' : do_something}) for u in self.urls) responses=grequests.map(unsentrequests) I prefer to use `requests` directly in a loop using `gevent` to have a more explicit code: import gevent.monkey gevent.monkey.patch_socket() from gevent.pool import Pool import requests def check_urls(urls): def fetch(url): response = requests.request('GET', url, timeout=5.0) print "Status: [%s] URL: %s" % (response.status_code, url) pool = Pool(20) for url in urls: pool.spawn(fetch, url) pool.join()
find a alpha-numeric entry in tab delimited file with python Question: I'm trying to perform a GOs annotation using the SIMAP database which is Blast2GO annotated. Everything is fine, but I have problems when I try to find the accession number in the file where entry numbers are associated with their GOs. The problem is that the script does not find the number in the input file when really there is. I tried several things without good results (re.match, insert in a list and then extract the element, etc) File where the GOs are associated with entry numbers has this structure (accession number, GO term, blats2go score): 1f0ba1d119f52ff28e907d2b5ea450db GO:0007154 79 1f0ba1d119f52ff28e907d2b5ea450db GO:0005605 99 The python code: import re from Bio.Blast import NCBIXML from Bio import SeqIO input_file = open('/home/fpiston/Desktop/test_go/test2.fasta', 'rU') result_handle = open('/home/fpiston/Desktop/test_go/test2.xml', 'rU') save_file = open('/home/fpiston/Desktop/test_go/test2.out', 'w') fh = open('/home/fpiston/Desktop/test_go/Os_Bd_Ta_blat2go_fake', 'rU') q_dict = SeqIO.to_dict(SeqIO.parse(input_file, "fasta")) blast_records = NCBIXML.parse(result_handle) hits = [] for blast_record in blast_records: if blast_record.alignments: list = (blast_record.query).split() if re.match('ENA|\w*|\w*', list[0]) != None: list2 = list[0].split("|") save_file.write('%s\t' % list2[1]) else: save_file.write('%s\t' % list[0]) for alignment in blast_record.alignments: for hsp in alignment.hsps: h = alignment.hit_def for l in fh: ls = l.split() #at this point all right if h in ls: #here, 'h' in not found in 'fh' print h print 'ok' save_file.write('%s\t' % ls[1]) save_file.write('\n') hits.append(blast_record.query.split()[0]) misses =set(q_dict.keys()) - set(hits) for i in misses: list = i.split("|") if len(list) > 1: save_file.write('%s\t' % list[1]) else: save_file.write('%s\t' % list) save_file.write('%s\n' % 'no_match') save_file.close() This is the code with the correction of **martineau** (fh.seek(0)): #!/usr/bin/env python import sys import re from Bio.Blast import NCBIXML from Bio import SeqIO input_file = sys.argv[1] #queries sequences in fasta format out_blast_file = sys.argv[2] #name of the blast results file output_file = sys.argv[3] #name of the output file result_handle = open(out_blast_file, 'rU') fh = open('/home/fpiston/Desktop/test_go/Os_Bd_Ta_blat2go', 'rU') q_dict = SeqIO.to_dict(SeqIO.parse(open(input_file), "fasta")) blast_records = NCBIXML.parse(result_handle) save_file = open(output_file, 'w') hits = [] for blast_record in blast_records: if blast_record.alignments: list = (blast_record.query).split() if re.match('ENA|\w*|\w*', list[0]) != None: list2 = list[0].split("|") save_file.write('\n%s\t' % list2[1]) else: save_file.write('\n%s\t' % list[0]) for alignment in blast_record.alignments: for hsp in alignment.hsps: hit = alignment.hit_def save_file.write('%s\t' % hit) fh.seek(0) for l in fh: ls = l.split() if ls[0] in hit: save_file.write('%s\t' % ls[1]) hits.append(blast_record.query.split()[0]) misses =set(q_dict.keys()) - set(hits) for i in misses: list = i.split("|") if len(list) > 1: save_file.write('\n%s\t' % list[1]) else: save_file.write('\n%s\t' % list) save_file.write('%s' % 'no_match') save_file.close() Answer: I really have no idea what you're talking about here, but noticed that within the outer `for blast_record in blast_records:` and `for alignment in blast_record.alignments:` loops you have a `for l in fh:` but never rewind the file with a `fh.seek(0)` anywhere, which means it only reads the lines in the file the first time it's executed -- which seems illogical. You could fix this by adding the `fh.seek(0)` just before the inner loop. Although unnecessary the very first time the inner loop executes, it's need all the following times and doing it one extra time won't hurt anything.
Python summing itertools.count? Question: I'm having some trouble with the itertools.count function, and I don't quite understand what it does. I expect the code below to accomplish [Project Euler problem 2](http://projecteuler.net/problem=2). I know that I could write this with a simple while loop, but is there a way to do it with a list comprehension? This code just freezes as I guess it's going to go infinity with count(). I would have hoped it would stop after x > MAX, but I know that won't happen. Is there a way to stop count in a generator expression like below? def fib(n): if (n <= 1): return 1 else: return fib(n-1) + fib(n-2) MAX = 4000000 infiniteFib = (fib(x) for x in count()) s = (x for x in infiniteFib if x < MAX and x % 2 == 0) print sum(s) Answer: You could use [`takewhile`](http://docs.python.org/2/library/itertools.html#itertools.takewhile): >>> from itertools import count, takewhile, imap >>> sum(x for x in takewhile(lambda x: x < 4000000, imap(fib, count())) if x % 2 == 0) 4613732
Color a particular node in Networkx and Graphviz Question: I am writing a program to plot a graph from a distance matrix. It is working fine. Now I want a certain node and a certain edge to be of a particular color of my choice. How do I do that? The program is in Python and uses Networkx and Graphviz import networkx as nx import numpy as np import pickle from random import randint p_file = open('pickles/distance') Dist = pickle.load(p_file) p_file.close() p_file = open('pickles/names') Names = pickle.load(p_file) p_file.close() dt = [('len', float)] A = np.array(Dist)*5 A = A.view(dt) G = nx.from_numpy_matrix(A) G = nx.relabel_nodes(G, dict(zip(range(len(G.nodes())),Names))) G = nx.to_agraph(G) G.node_attr.update(ndcolor="red", node="DC", style="filled") G.edge_attr.update(color="none") G.draw('P1.png', format='png', prog='neato') Answer: Since you are using Graphviz to do the drawing you need to use the attributes that Graphviz understands. See <http://www.graphviz.org/content/attrs> import networkx as nx G = nx.Graph() G.add_node(1,color='red',style='filled',fillcolor='blue',shape='square') G.add_node(2,color='blue',style='filled') G.add_edge(1,2,color='green') G.node[2]['shape']='circle' G.node[2]['fillcolor']='red' A = nx.to_agraph(G) A.layout() A.draw('color.png') print A.to_string() Gives strict graph { graph [bb="0,0,107.21,46.639"]; node [label="\N"]; 1 [color=red, fillcolor=blue, height=0.5, pos="18,28.639", shape=square, style=filled, width=0.5]; 2 [color=blue, fillcolor=red, height=0.5, pos="89.21,18", shape=circle, style=filled, width=0.5]; 1 -- 2 [color=green, pos="36.338,25.899 47.053,24.298 60.519,22.286 71.18,20.694"]; } ![enter image description here](http://i.stack.imgur.com/lcUfo.png)
Import from parent directory failed with ImportError Question: I'm busy developing an application in python, my application is structured as follows main.py pr/ core/ __init__.py predictor.py gui/ predictor/ __init__.py predict_panel.py __init__.py pr_app.py __init__.py I launch the application using `main.py` inside `pr_app.py` I've got class PrApp(wx.App): PREDICTOR = Predictor() inside `predict_panel.py` I can successfully do `from pr.core.predictor import Predictor` but for some reason I cannot do `from pr.gui.pr_app import PrApp` I get presented with `ImportError: cannot import name PrApp` Is there some kind of gotcha when importing from parent directories in python, or am I missing something? Answer: I tried this and made a tree like yours, but with the addition of an `__init__.py` in the `pr` directory. Without that `__init__.py` your `from pr.core.predictor import Predictor` should fail, so I think you have it, but forgot to write it in your question. I was not able to get the failure you did, it worked fine for me. I can do both imports from `predict_panel.py`, as I expected to. However, if I from `pr_app.py` import `predict_panel`, then the import from `predict_panel.py` of `PrApp` will fail. This is because I have a circular import. You try to import `predict_panel` from `PrApp` during the import of `PrApp` and you try to import `PrApp` during the import of `predict_panel`. That would create an infinite recursion of imports, so it is not allowed. The best way to solve this is to reorganize your code so you don't have to do circular imports. If `PrApp` imports `predict_panel`, why would `predict_panel` need `PrApp`? That's a sign of a flawed design. However, the quickest way to fix it is to move one of the imports from the top of the module into the function/method where it's called. That's bad practice, but it will fix your problem quickly.
Understanding Python's backslash escape character Question: My script creates files to export by concatenating a file path with a file type suffix. For example, int = 3 print r"C:\Test\\" + str(int) + ".jpg" This returns `C:\Test\\3.jpg` I thought that because I included the 'r' at the beginning, I wouldn't need a double backslash at the end, because it'd be treated as a raw string. But the following doesn't work: int = 3 print r"C:\Test\" + str(int) + ".jpg" ...presumably because Python is seeing an escape character before the end quote. So what's the point of the 'r' then? And while my files get saved in the right place when exported, I don't like that the print command gives me two backslashes after Test (eg C:\Test\3.jpg) when it just gives me one after C: How can I get a single backslash in my file paths please? Thanks Answer: Don't try and use string manipulation to build up file paths. Python has the `os.path` module for that: import os.path i = 3 print os.path.join("C:\Test", str(i) + ".jpg") This will ensure the path is constructed properly. (Also, don't call an integer `int`, as it shadows the built-in `int()` function.)
launching python script process from another script on Ubuntu: how to track status? Question: I launch one Python script out of another one on an Amazon EC2 Ubuntu instance using a command: os.system(call) where `call` has the form "./script2.py arg1 arg2 arg3" I've noticed that from time to time `script2.py` somehow terminates prematurely. I have some logging statements in it but they don't show what's going on. So my questions are: 1. I read that `system()` returns some sort of exit status. What's the best test to distinguish between a normal and abnormal termination? That is, I only want to produce a log message inside the calling script if there is some sort of abnormal termination. 2. Is there any sort of system log where I could try to find traces of terminated processes? Answer: Assuming that your child script does not use standard output for something and returns non-zero on a crash (this should be default for `python` executable though): import subprocess as sp try: sp.check_output(['python', 'child.py'], stderr=sp.STDOUT) except sp.CalledProcessError as err: print 'Child terminated abnormally with error %d, log:' % err.returncode print err.output
What does this (matplotlib) error message mean? Question: Display is the module: import matplotlib matplotlib.use('TkAgg') #TkAgg is quite slow but should work on all platforms. import time import numpy import matplotlib.pyplot as plt def display_2d_array(arr): '''Display a square 2D numpy array as a greyscale image.''' assert len(arr.shape) == 2 and arr.shape[0] == arr.shape[1] plt.ion() plt.clf() plt.imshow(arr,origin="lower",extent=[0,arr.shape[0],0,arr.shape[0]]) plt.gray() plt.draw() raw_input('Hit enter to continue.') But when I call it in a module I get: File "/Users/tomkimpson/display.py", line 8, in <module> import matplotlib.pyplot as plt File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site packages/matplotlib/pyplot.py", line 26, in <module> from matplotlib.figure import Figure, figaspect File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- packages/matplotlib/figure.py", line 24, in <module> import matplotlib.artist as martist File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/artist.py", line 7, in <module> from transforms import Bbox, IdentityTransform, TransformedBbox, \ File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/transforms.py", line 35, in <module> from matplotlib._path import (affine_transform, count_bboxes_overlapping_bbox, ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- packages/matplotlib/_path.so, 2): no suitable image found. Did find: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- packages/matplotlib/_path.so: no matching architecture in universal wrapper Anyone any idea what this means?! Answer: It looks like you're running this on OS X. Take a look at this [this question](http://stackoverflow.com/questions/7157330/problem-importing- matplotlib-mlab-and-pyplot-in-python-2-7-on-mac-osx-10-6), where another OS X user had your same error. Your matplotlib install is probably corrupted. The marked answer in question linked to [this page](http://telliott99.blogspot.com/2011/07/matplotlib-on-os-x-lion- revised.html), which details how to install matplotlib on OS X.
Using Python CGI and MySQL to save the user inputed from a form into MySQL table Question: I have two .cgi scripts as of right now. I am trying to have a user input a keyword on one website (the first cgi script) and then it will send that data to the next cgi script. It currently sends it to the next page fine but I also want to save the information the user types in to a MySQL table named "keywords". I am having trouble figuring out how exactly to do that. Here is my first cgi script that prompts the user for a keyword: #!/usr/bin/env python import cgi import cgitb cgitb.enable() form = cgi.FieldStorage() keyword = form.getvalue('keyword') print 'Content-type: text/html\r\n\r' print '<html>' print '<h1>Please enter a keyword of your choice</h1>' print '<form action="results.cgi" method="post">' print 'Keyword: <input type="text" name="keyword"> <br />' print '<input type="submit" value="Submit" />' print '</form>' print '</html>' Here is my second .cgi file. In this I am trying to print the keyword that was typed in from the previous page (that works fine) and also send it and save it my mysql table (thats where the problem is): cgitb.enable() form = cgi.FieldStorage() keyword = form.getvalue('keyword') print 'Content-type: text/html\r\n\r' print '<html>' print keyword print '</html>' db = MySQLdb.connect(host="", user="", passwd="", db="") cursor = db.cursor() sql = """INSERT INTO keywords(keywords) VALUES (keywords)""" cursor.execute(sql) cursor.fetchall() db.close() Basically I am new to MySQL in general and I'm pretty sure it comes down to my mysql code being all messed up and doing what I want it to do. It doesn't fetch any errors, just doesn't add anything to the table. Answer: You're not passing any parameter to the `cursor.execute` method. You'll need: sql = "INSERT INTO keywords (keywords) VALUES (%s)" cursor.execute(sql, keyword) This should work, supposing your table is called `keywords` and contains a column called `keywords`. You can [have a look at the `MySQLdb` user guide](http://mysql- python.sourceforge.net/MySQLdb.html) for more information. * * * Please realize that this simple app is exposed to most of the security vulnerabilities a webapp could be vulnerable to (except for SQL injection), which notably includes [XSS attacks](http://en.wikipedia.org/wiki/Cross- site_scripting).
AttributeError: based on re.compile pattern Question: I'm new at Python, and I'm pretty sure that the cause of this is simply a blonde moment, but it's been driving me up the wall the past few days. I keep getting "elif conName.search(line): AttributeError: 'list' object has no attribute 'search'" on line 106 If I replace the pattern in line 54 with the one from line 50, then lines 106-113 run fine, but I get the same error on line 114. When I comment out lines 105-123, the remainder of the code works finest kind. When I comment out lines 106-109, then lines 110-113 run fine, but I get the same error on line 114. ## This should be line 19 html_doc = """ <title>Flickr: username</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta property="og:title" content="username" /> <meta property="og:type" content="flickr_photos:profile" /> <meta property="og:url" content="http://www.flickr.com/people/Something/" /> <meta property="og:site_name" content="Flickr" /> <meta property="og:image" content="http://farm79.staticflickr.com/1111/buddyicons/[email protected]?1234567890#99999999@N99" /> <li> <a href="/groups/theportraitgroup/">The Portrait Group</a> <span class="text-list-item"> 1,939,830 photos,&nbsp;125,874 members </span> </li> <li> <a href="/groups/412762@N20/">Seagulls Gone Wild</a> <span class="text-list-item"> 2,266 photos,&nbsp;464 members </span> </li> """ from urllib.request import urlopen from bs4 import BeautifulSoup import fileinput import re ## This should be line 46 ## Strips for basic group data Tab = re.compile("(\t){1,}") # strip tabs ID = re.compile("^.*/\">") # Group ID, could be ID or Href Href = re.compile("(\s)*<a href=\"/groups/") # Strips to beginning of ID GName = re.compile("/\">(<b>)*") # Strips from end of Href to GName ## Persons contact info conName = re.compile("(\s)*<meta property=\"og\:title\" content=\"") # Contact Name ##conName = re.compile("(\s)*<a href=\"/groups/") conID = re.compile("(\s)*<meta property=\"og\:image.*\#") # Gets conName's @N ID conRef = re.compile("(\s)*<meta property=\"og\:url.*com/people/") Amp = re.compile("&amp;") Qt = re.compile("&quot;") Gt = re.compile("&gt;") Lt = re.compile("&lt;") exfile = 1 ## 0 = use internal data, 1 = use external file InFile = html_doc if exfile: InFile = open('\Python\test\Group\group 50 min.ttxt', 'r', encoding = "utf-8", errors = "backslashreplace") closein = 1 ## Only close input file if it was opened else: closein = 0 OutFile = open('C:\Python\test\Group\Output.ttxt', 'w', encoding = "utf-8", errors = "backslashreplace") cOutFile = open('C:\Python\test\Group\ContactOutput.ttxt', 'w', encoding = "utf-8", errors = "backslashreplace") i = 1 ## counter for debugging ## This should be line 80 for line in InFile: ## print('{}'.format(i), end = ', ') ## this is just a debugging line, to see where the program errors out ## i += 1 if Href.search(line): ln = line ln = re.sub(Href, "", ln) gID, Name = ln.split("/\">") Name = Name[:-5] ## this removes the "\n" at EOL as well if "@N" in gID: rH = "" else: rH = gID gID = "" ## sLn = '{3}\t{0}\t{1}\t{2}\n'.format(Name, gID, rH, conName) sLn = '{0}\t{1}\t{2}\n'.format(Name, gID, rH, conName) ## Replace HTML codes sLn = re.sub(Gt, ">", sLn) sLn = re.sub(Lt, "<", sLn) sLn = re.sub(Qt, "\"", sLn) sLn = re.sub(Amp, "&", sLn) OutFile.write(sLn) ## This should be line 104 ################################################# elif conName.search(line): ln = line ln = re.sub(conName, "", ln) conName = ln.split("\" />") elif conID.search(line) is not None: ln = line ln = re.sub(conID, "", ln) conID = ln.split("\" />") elif conRef.search(line) is not None: ln = line ln = re.sub(conRef, "", ln) conRef = ln.split("\" />") else: pass sLn = '{0}\t{1}\t{2}\n'.format(conID, conRef, conName) cOutFile.write(sLn) ## I know, this will make a massive file with duplicated data, but deal w/ it later ################################################# if closein: InFile.close() OutFile.close() cOutFile.close() Does anyone have any ideas? Thank you! Answer: > I keep getting "elif conName.search(line): AttributeError: 'list' object has > no attribute 'search'" on line 106 It means that `conName` is a list at this moment. And indeed 2 lines below you assign `conName` to a list: conName = ln.split("\" />") After the first `conName.search()` returned a successful match you changed it to a list so for the following lines from the file (the next loop iterations) `conName.search` produces the error.
Saving data from MySQL table to a text file with Python Question: So I have a mysql table and I am trying to take each element from one of the fields of the table. The field and table are both called "keywords". In the field there are many different random words and I am trying to take all of those and save them to a text file. Any help on how to implement this would be great, here is what I have so far. #!/usr/bin/env python import MySQLdb db = MySQLdb.connect(host="", user="", passwd="", db="") cursor = db.cursor() sql = """SELECT DISTINCT keywords FROM keywords""" cursor.execute(sql) cursor.fetchall() db.close() for s in sql: tweets = open("keywords.txt", "w") What I was thinking is to turn what sql fetches into a list if possible and write that to the file. But I am open to any suggestions, thanks. Answer: Something like this should work: import MySQLdb db = MySQLdb.connect(host="", user="", passwd="", db="") cursor = db.cursor() sql = """SELECT DISTINCT keywords FROM keywords""" tweets = open("keywords.txt", "w") cursor.execute(sql) for row in cursor: print>>tweets, row[0] tweets.close() db.close()
Python user input in child process Question: I'm trying to create a child process that can take input through raw_input() or input(), but I'm getting an end of liner error _EOFError: EOF_ when asking for input. I'm doing this to experiment with multiprocessing in python, and I remember this easily working in C. Is there a workaround without using pipes or queues from the main process to it's child ? I'd really like the child to deal with user input. def child(): print 'test' message = raw_input() #this is where this process fails print message def main(): p = Process(target = child) p.start() p.join() if __name__ == '__main__': main() I wrote some test code that hopefully shows what I'm trying to achieve. Answer: My answer is taken from here: [Is there any way to pass 'stdin' as an argument to another process in python?](http://stackoverflow.com/questions/8976962/is- there-any-way-to-pass-stdin-as-an-argument-to-another-process-in-python) I have modified your example and it seems to work: from multiprocessing.process import Process import sys import os def child(newstdin): sys.stdin = newstdin print 'test' message = raw_input() #this is where this process doesn't fail anymore print message def main(): newstdin = os.fdopen(os.dup(sys.stdin.fileno())) p = Process(target = child, args=(newstdin,)) p.start() p.join() if __name__ == '__main__': main()
how to show txt on web, by gae,google app engine,python Question: i want to upload txt file and show this txt. i had the code of uploading txt to gae, but how to show it??? i want to upload txt file and show this txt. i had the code of uploading txt to gae, but how to show it??? i want to upload txt file and show this txt. i had the code of uploading txt to gae, but how to show it??? import os import urllib from google.appengine.ext import blobstore from google.appengine.ext import webapp from google.appengine.ext.webapp import blobstore_handlers from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app class MainHandler(webapp.RequestHandler): def get(self): upload_url = blobstore.create_upload_url('/upload') self.response.out.write('<html><body>') self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url) self.response.out.write("""Upload File: <input type="file" name="file"><br> <input type="submit" name="submit" value="Submit"> </form></body></html>""") for b in blobstore.BlobInfo.all(): self.response.out.write('<li><a href="/serve/%s' % str(b.key()) + '">' + str(b.filename) + '</a>') class UploadHandler(blobstore_handlers.BlobstoreUploadHandler): def post(self): upload_files = self.get_uploads('file') blob_info = upload_files[0] self.redirect('/') class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler): def get(self, blob_key): blob_key = str(urllib.unquote(blob_key)) if not blobstore.get(blob_key): self.error(404) else: self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True) def main(): application = webapp.WSGIApplication( [('/', MainHandler), ('/upload', UploadHandler), ('/serve/([^/]+)?', ServeHandler), ], debug=True) run_wsgi_app(application) if __name__ == '__main__': main() Answer: you should change the redirect function of your upload handler a bit, in the end you should redirect to the uploaded file: self.redirect('/serve/%s/' % blob_info.key()) also, your servehandler (i'm not sure you can use this tho, it may be better if you created your own serve_txt function, i'll try anyway) class ServeHandler(webapp.RequestHandler): #we want to render a page, not a download, that's why it extends RequestHandler def get(self, resource): resource = str(urllib.unquote(resource)) blob_info = blobstore.BlobInfo.get(resource) #this should be your file self.response.headers['Content-Type'] = 'text/html' self.response.out.write(blob_info) templating is completely up to you now, this should display a plain text to your page (being a txt, you may want to read it before with python using [BlobReader class](https://developers.google.com/appengine/docs/python/blobstore/blobreaderclass) then return the page correctly formatted. mine is just an example on how you should proceed)
Creating dynamic objects with | separator python Question: What I want is to solve is something like this names = ['Aleister', 'Matovu'] args = (Q(name__contains=name[0])|Q(name__contains=name[1])) queryset.complex_filter(args) What the problem is I have a names as a dynamic object and its length is not fixed. What I am thinking would work is if I looped though the names and created a dynamic `args` object but I am not sure what kind of object that is. I am not sure how exactly to do that, so I am stuck. If you can help around that, that will be really cool or if you can give me an alternative way to go about the same scenario that would be awesome. Thank you Answer: import operator names = [...] query = reduce(operator.or_, [Q(name__icontains=name) for name in names]) results = queryset.complex_filter(query)
Python cannot import name if placed in module Question: > **Possible Duplicate:** > [How to do relative imports in > Python?](http://stackoverflow.com/questions/72852/how-to-do-relative- > imports-in-python) I'm experiencing something that seems very random to me. I have a folder structure much like this: dir A __init__.py is empty a.py imports stuff and b.py dir B __init__.py is empty b.py imports NOTHING a.py raises an error (cannot import name b). This only happens while b is part of module B. If I move it outside the directory, the import error does NOT occur. Any help would be appreciated. I must be overlooking something. Answer: Did you try the [relative import](http://docs.python.org/2/tutorial/modules.html#intra-package- references) from ..B import b ? * * * EDIT: This does not apply if it doesn't matter where package `B` lives. But you don't describe what exactly you do. As you may know or not, there are several import forms: import module import package # imports package.__init__ under the name package import package.module from package import module import package from module import component from package.module import component As you only write > a.py imports stuff and b.py I don't know what exactly happens: if you try to import b that fails because `b` lives in the package `B`. So you need one of from B import b import B.b Your comment above mentions a name clash. Which of two equally named packages and modules have priority depends on in which directory you are: `'.'` is normally at the very start of `sys.path`, so if you are directly under your `utils` directory you might have a different experience than otherwise.
Python: shorter syntax for slices with gaps? Question: Suppose I want the first element, the 3rd through 200th elements, and the 201st element through the last element by step-size 3, from a list in Python. One way to do it is with distinct indexing and concatenation: new_list = old_list[0:1] + old_list[3:201] + old_list[201::3] Is there a way to do this with just one index on `old_list`? I would like something like the following (I know this doesn't syntactically work since list indices cannot be lists and since Python unfortunately [doesn't have slice literals](http://stackoverflow.com/questions/13706258/passing-python- slice-syntax-around-to-functions); I'm just looking for something close): new_list = old_list[[0, 3:201, 201::3]] I can achieve some of this by switching to NumPy arrays, but I'm more interested in how to do it for native Python lists. I could also create [a slice maker](http://stackoverflow.com/questions/13706258/passing-python-slice- syntax-around-to-functions) or something like that, and possibly strong arm that into giving me an equivalent slice object to represent the composition of all my desired slices. But I'm looking for something that doesn't involve creating a new class to manage the slices. I want to just sort of concatenate the slice syntax and feed that to my list and have the list understand that it means to separately get the slices and concatenate their respective results in the end. Answer: A slice maker object (e.g. `SliceMaker` from your other question, or `np.s_`) can accept multiple comma-separated slices; they are received as a `tuple` of `slice`s or other objects: from numpy import s_ s_[0, 3:5, 6::3] Out[1]: (0, slice(3, 5, None), slice(6, None, 3)) NumPy uses this for multidimensional arrays, but you can use it for slice concatenation: def xslice(arr, slices): return sum((arr[s] if isinstance(s, slice) else [arr[s]] for s in slices), []) xslice(range(10), s_[0, 3:5, 6::3]) Out[1]: [0, 3, 4, 6, 9]
Extract Public Key in Python OpenSSL (pyOpenSSL) from certificate or other connection information Question: I'm currently trying to write a python server script which should authenticate the current client based on its public key. Since I'm using twisted, the [example in the twisted documenteation](http://twistedmatrix.com/documents/11.0.0/core/howto/ssl.html#auto7) got me started. While I can generate keys, connect and communicate using the example code, I have not yet found a way to get the public key of the client in a usable format. In [this stackexchange question](http://stackoverflow.com/questions/10362965/how-to-get-public-key- using-pyopenssl) somebody extracts the public key from an `OpenSSL.crypto.PKey` object but cannot transform it to a readable format. Since in I have access to the `PKey` object of the x509 certificate in the `verifyCallback` method or via `self.transport.getPeerCertificate()` from any method of my Protocol, this would be a good way to go. The (not accepted) answer suggests to try `crypto.dump_privatekey(PKey)`. Unfortunately, this does not really yield the expected result: While the `BEGIN PRIVATE KEY` and `BEGIN PRIVATE KEY` in the answer could be fixed by an easy text replacement function, the base64 string seems not match the public key. I've extracted the public key with `openssl rsa -in client.key -pubout > client.pub` as mentioned [here](http://stackoverflow.com/questions/10271197/openssl-how-to-extract- public-key). It does not match the result of the `dump_privatekey` function. While there still is an [open bug towards OpenSSL on launchpad](https://bugs.launchpad.net/pyopenssl/+bug/780089), it is not yet fixed. It was reported 19 Month ago, and there is some recent (October 2012) activity on it, I do not have any hope of a fast fix in the repos. Do you have any other ideas how I could get the public key in a format comparable to the `client.pub` file I have mentioned above? Perhaps there is a twisted or OpenSSL connection specific object which holds this information. Please note that I have to store the public key in the protocol object such that I can access it later. ## Why is no Answer accepted? ### M2Crypto by J.F. Sebastian Sorry, that I had not thought of a possibility where I cannot correlate the certificate to the connection. I've added the requirement that I have to store the public key inside the protocol instance. Thus, using `peerX509.as_pem()` inside the `postConnectionCheck` function as suggested by J.F. Sebastian does not work. Furthermore, at least in version 0.21.1-2ubuntu3 of python-m2crypto I have to call `peerX509.get_rsa().as_pem()` to get the right public key. Using `peerX509.as_pem(None)` (since `peerX509.as_pem()` still wants a passphrase) yields excactly the same output as `crypto.dump_privatekey(PKey)` in PyOpenSSL. Maybe there is a bug. Besides this, the answer showed me a possible way to write another workaround by using the following `Echo` protocol class: class Echo(Protocol): def dataReceived(self, data): """As soon as any data is received, write it back.""" if self.transport.checked and not self.pubkeyStored: self.pubkeyStored = True x509 = m2.ssl_get_peer_cert(self.transport.ssl._ptr()) if x509 is not None: x509 = X509.X509(x509, 1) pk = x509.get_pubkey() self.pubkey = pk.get_rsa().as_pem() print pk.as_pem(None) print self.pubkey self.transport.write(data) As you can see this uses some internal classes which I'd like to prevent. I'm hesitating submitting a small patch which would add a `getCert` method to the `TLSProtocolWrapper` class in M2Crypto.SSL.TwistedProtocolWrapper. Even if it was accepted upstream, it would break compatibility of my script with any but the most cut-of-the-edge versions of m2crypto. What would you do? ### External OpenSSL call by me Well, its an ugly workaround based on external system commands just which seems to me even worse than accessing non-public attributes. Answer: Some of previous answers produce (apparently?) working PEM public key files, but so far as I've tried, none of them produce the same output that the 'openssl rsa -pubout -in priv.key' does. This is pretty important to my test suite, and after poking around in the (0.15.1) PyOpenSSL code, this works well for both standard PKey objects and the public-key-only PKey objects created by the x509.get_pubkey() method: from OpenSSL import crypto from OpenSSL._util import lib as cryptolib def pem_publickey(pkey): """ Format a public key as a PEM """ bio = crypto._new_mem_buf() cryptolib.PEM_write_bio_PUBKEY(bio, pkey._pkey) return crypto._bio_to_string(bio) key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, 2048) print pem_publickey(key)
Python 3.3 Mysql Connector Question: > **Possible Duplicate:** > [MySQL-db lib for Python > 3.0?](http://stackoverflow.com/questions/384471/mysql-db-lib-for-python-3-0) I use python3.3 and can't connect to MySQL, because I don't find module for MySQL connector. How do I connect to MySQL with python3.3? Answer: There is a module called [Pymysql](https://github.com/petehunt/PyMySQL/) which you may like: """This pure Python MySQL client provides a DB-API to a MySQL database by talking directly to the server via the binary client/server protocol.""" import pymysql conn = pymysql.connect(host='127.0.0.1', unix_socket='/tmp/mysql.sock', user='root', passwd=None, db='mysql') cur = conn.cursor() cur.execute("SELECT Host,User FROM user") for response in cur: print(response) cur.close() conn.close()
Convert JSON to CSV using Python (Idle) Question: I have a JSON file of Latitude/Longitude that I want to covert to a CSV file. I want to do this using Python. I have read/tried all other stackoverflow and google search results suggestions. I've managed to get as far as creating the CSV and including headers, but beyond that, goofy stuff starts to happen. Here is the working part of my code so far: import json, csv x="""[ {"longitude":"-73.689070","latitude":"40.718000"}, {"longitude":"-73.688400","latitude":"40.715990"}, {"longitude":"-73.688340","latitude":"40.715790"}, {"longitude":"-73.688370","latitude":"40.715500"}, {"longitude":"-73.688490","latitude":"40.715030"}, {"longitude":"-73.688810","latitude":"40.714370"}, {"longitude":"-73.688980","latitude":"40.714080"}, {"longitude":"-73.689350","latitude":"40.713390"}, {"longitude":"-73.689530","latitude":"40.712800"}, {"longitude":"-73.689740","latitude":"40.712050"}, {"longitude":"-73.689820","latitude":"40.711810"}, {"longitude":"-73.689930","latitude":"40.711380"}, {"longitude":"-73.690110","latitude":"40.710710"} ]""" x = json.loads(x) f = csv.writer(open("test.csv", "wb+")) f.writerow(["longitude", "latitude"]) And here's where it falls apart ("?'s" mean I'm not sure what to put there. I've tried all sorts of combinations of things that I've found in my search for answers): for ? in ?: f.writerow([?[?],?[?]]) I got the above from answers to [this question](http://stackoverflow.com/questions/1871524/convert-from-json-to-csv- using-python) by [little_fish](http://stackoverflow.com/users/227684/little- fish). I can see that our JSON examples are slightly different, and I am assuming that has something to do with why I can't get it to work... Any help would be greatly appreciated, and I am happy to provide clarification if need be. FYI, I am new to Python, so if you're going to use jargon, please explain it as clearly as possible. Thanks! (P.S. Not sure if it matters, but I am using IDLE). Answer: I would use a [csv.DictWriter](http://docs.python.org/2/library/csv.html#csv.DictWriter), since you're dealing with dicts, which is exactly the case `DictWriter` is there for. rows = json.loads(x) with open('test.csv', 'wb+') as f: dict_writer = csv.DictWriter(f, fieldnames=['longitude', 'latitude']) dict_writer.writeheader() dict_writer.writerows(rows) **Edit:** Since the `.writeheader()` method was only added in 2.7, you can use something like this on older versions: rows = json.loads(x) fieldnames = ['longitude', 'latitude'] with open('test.csv', 'wb+') as f: dict_writer = csv.DictWriter(f, fieldnames=fieldnames) dict_writer.writerow(dict(zip(fieldnames, fieldnames))) dict_writer.writerows(rows)
How can I dynamically execute function in current scope and add it as property of the calling function? Question: I have some code like this: def f1(): <some stuff here> . . . @mylib.codegen def f2(args): f1() <some more stuff here> mylib.py : def codegen(fn): src = inspect.getsource(fn) original_ast = ast.parse(src) new_ast = transform_ast(original_ast) code_obj = compile(new_ast, '<auto-generated>', 'exec') myscope = {} exec code_obj in myscope fn.generated_fn = myscope['name'] # Where name is the binding created by execing code_obj To summarize, `mylib.codegen` is a decorator which parses code of f, creates an ast of another function based on ast of `f`, execs code of generated function to get a callable function and sets callable function as a property of `f`. That means when `f2` is imported the first time, `f2` dynamically gets another function as property of itself. Generated function also needs to call `f1` but it can't find `f1` in `myscope`. If somehow Python allowed inlining, and I had inlined code of `mylib.codegen`, everything would have been fine but I don't think Python allows inlining of code. How do I set things up so that generated code object is execed in namespace of caller function? Answer: The `fn.func_globals` contains the global namespace for a given function; you'll need it to be able to exec the transformed and recompiled code object: myscope = {} myscope.update(fn.func_globals) Do not use `fn.func_globals` directly; you wouldn't want to overwrite items in that namespace.
python: Create file but if name exists add number Question: Does python have any built-in functionality for this? My idea is that it would work the way certain OS's work if a file is outputted to a directory where a file of that name already exists. I.e: if "file.pdf" exists it will create "file2.pdf", and next time "file3.pdf". Answer: In a way, Python has this functionality built into the `tempfile` module. Unfortunately, you have to tap into a private global variable, `tempfile._name_sequence`. This means that officially, `tempfile` makes no guarantee that in future versions `_name_sequence` even exists -- it is an implementation detail. But if you are okay with using it anyway, this shows how you can create uniquely named files of the form `file#.pdf` in a specified directory such as `/tmp`: import tempfile import itertools as IT import os def uniquify(path, sep = ''): def name_sequence(): count = IT.count() yield '' while True: yield '{s}{n:d}'.format(s = sep, n = next(count)) orig = tempfile._name_sequence with tempfile._once_lock: tempfile._name_sequence = name_sequence() path = os.path.normpath(path) dirname, basename = os.path.split(path) filename, ext = os.path.splitext(basename) fd, filename = tempfile.mkstemp(dir = dirname, prefix = filename, suffix = ext) tempfile._name_sequence = orig return filename print(uniquify('/tmp/file.pdf'))
Python Embedded in C++ Question: So I have a GUI program that has a great deal of "stuff" going on. I am adding a python scripting interface so someone can interact problematically with this environment. I am using boost python. So first thing I have is a new module I want to create. For simplicity right now my module just is hello world... #include <boost/python.hpp> char const* greet() { return "hello, world" ; } BOOST_PYTHON_MODULE(cerrnimapi) { boost::python::def( "greet", greet ) ; } In my system I have a class that looks like this... Controller::Controller( ) { Py_Initialize( ) ; main_module = boost::python::import( "__main__" ) ; main_namespace = main_module.attr( "__dict__" ) ; } void Controller::execute_script( std::string filename ) { try { boost::python::api::object ignored = boost::python::exec_file( filename.c_str(), main_namespace ) ; } catch( boost::python::error_already_set const & ) { if (PyErr_ExceptionMatches(PyExc_ZeroDivisionError)) { } else { PyErr_Print(); } } } Now when I go to execute the script in the GUI I get an error... Traceback (most recent call last): File "/home/mokon/repository/trunk/python.py", line 1, in <module> import cerrnimapi ImportError: No module named cerrnimapi So of course I am building something wrong. My build system uses autotools so here are a few pieces of that build system that relate to this... In configure.ac: AM_PATH_PYTHON AC_ARG_VAR([PYTHON_INCLUDE], [Include flags for python, bypassing python-config]) AC_ARG_VAR([PYTHON_CONFIG], [Path to python-config]) AS_IF([test -z "$PYTHON_INCLUDE"], [ AS_IF([test -z "$PYTHON_CONFIG"], [ AC_PATH_PROGS([PYTHON_CONFIG], [python$PYTHON_VERSION-config python-config], [no], [`dirname $PYTHON`]) AS_IF([test "$PYTHON_CONFIG" = no], [AC_MSG_ERROR([cannot find python-config for $PYTHON.])]) ]) AC_MSG_CHECKING([python include flags]) PYTHON_INCLUDE=`$PYTHON_CONFIG --includes` AC_MSG_RESULT([$PYTHON_INCLUDE]) ]) AC_ARG_VAR([PYTHON_LD], [Linker flags for python, bypassing python-config]) AS_IF([test -z "$PYTHON_LD"], [ AS_IF([test -z "$PYTHON_CONFIG"], [ AC_PATH_PROGS([PYTHON_CONFIG], [python$PYTHON_VERSION-config python-config], [no], [`dirname $PYTHON`]) AS_IF([test "$PYTHON_CONFIG" = no], [AC_MSG_ERROR([cannot find python-config for $PYTHON.])]) ]) AC_MSG_CHECKING([python linker flags]) PYTHON_LD=`$PYTHON_CONFIG --ldflags` AC_MSG_RESULT([$PYTHON_LD]) ]) In my obj/ dir Makefile.am... pyexec_LTLIBRARIES = cerrnimapi.la cerrnimapi_la_SOURCES = ${SRC_DIR}/lib/PythonAPI.cpp cerrnimapi_la_LDFLAGS = -avoid-version -module $(PYTHON_LD) cerrnimapi_la_CXXFLAGS = $(PYTHON_INCLUDE) My makefile builds the shared lib and its in the obj folder along with my main program. This doesn't help. I have also done a make install to install the cerrnimapi lib in the python folders. This doesn't help. I have also tried adding the PythonAPI.cpp to my main programs SOURCES but to no avail. Any ideas? let me know what additional information would be helpful. Answer: Some things to check: * Run `nm` over your .so file (which might be in `.libs`) to make sure your module init func is exported. * Make your program print out the value of `sys.path` (use PyRun_SimpleString) to see where it's expecting your module to turn up. If you're defining modules for your interpreter only, you probably don't want to install them in `$pyexecdir`. * Read the [Extending Embedded Python](http://docs.python.org/2/extending/embedding.html#extending-embedded-python) article. You don't really need to build dynamic libraries at all, unless you're trying for a plugin architecture. A point on style: You should try and find `$PYTHON_CONFIG` outside of your tests for `$PYTHON_INCLUDE` and `$PYTHON_LD` so you're not doing the `AC_PATH_PROGS` twice: AM_PATH_PYTHON AC_ARG_VAR([PYTHON_CONFIG], [Path to python-config]) AS_IF([test -z "$PYTHON_CONFIG"], [ AC_PATH_PROGS([PYTHON_CONFIG], [python$PYTHON_VERSION-config python-config], [no], [`dirname $PYTHON`]) ]) AC_ARG_VAR([PYTHON_INCLUDE], [Include flags for python, bypassing python-config]) AS_IF([test -z "$PYTHON_INCLUDE"], [ AC_MSG_CHECKING([python include flags]) AS_IF([test "$PYTHON_CONFIG" = no], [AC_MSG_ERROR([cannot find python-config for $PYTHON.])]) PYTHON_INCLUDE=`$PYTHON_CONFIG --includes` AC_MSG_RESULT([$PYTHON_INCLUDE]) ]) AC_ARG_VAR([PYTHON_LD], [Linker flags for python, bypassing python-config]) AS_IF([test -z "$PYTHON_LD"], [ AC_MSG_CHECKING([python linker flags]) AS_IF([test "$PYTHON_CONFIG" = no], [AC_MSG_ERROR([cannot find python-config for $PYTHON.])]) PYTHON_LD=`$PYTHON_CONFIG --ldflags` AC_MSG_RESULT([$PYTHON_LD]) ])
Python json dumps syntax error when appending list of dict Question: I got two functions that return a list of dictionary and i'm trying to get json to encode it, it works when i try doing it with my first function, but now i'm appending second function with a syntax error of `": expected"`. I will eventually be appending total of 7 functions that each output a list of dict. Is there a better way of accomplishing this? import dmidecode import simplejson as json def get_bios_specs(): BIOSdict = {} BIOSlist = [] for v in dmidecode.bios().values(): if type(v) == dict and v['dmi_type'] == 0: BIOSdict["Name"] = str((v['data']['Vendor'])) BIOSdict["Description"] = str((v['data']['Vendor'])) BIOSdict["BuildNumber"] = str((v['data']['Version'])) BIOSdict["SoftwareElementID"] = str((v['data']['BIOS Revision'])) BIOSdict["primaryBIOS"] = "True" BIOSlist.append(BIOSdict) return BIOSlist def get_board_specs(): MOBOdict = {} MOBOlist = [] for v in dmidecode.baseboard().values(): if type(v) == dict and v['dmi_type'] == 2: MOBOdict["Manufacturer"] = str(v['data']['Manufacturer']) MOBOdict["Model"] = str(v['data']['Product Name']) MOBOlist.append(MOBOdict) return MOBOlist def get_json_dumps(): jsonOBJ = json #Syntax error is here, i can't use comma to continue adding more, nor + to append. return jsonOBJ.dumps({'HardwareSpec':{'BIOS': get_bios_specs()},{'Motherboard': get_board_specs()}}) Answer: Use multiple items within your nested dictionary. jsonOBJ.dumps({ 'HardwareSpec': { 'BIOS': get_bios_specs(), 'Motherboard': get_board_specs() } }) And if you want multiple `BIOS` items or `Motherboard` items, just use a list. ... 'HardwareSpec': { 'BIOS': [ get_bios_specs(), get_uefi_specs() ] ... }
Progressbar and combinations in Python Question: I am using itertools.combinations module to find a large number of combinations. While my program finds all its combinations (a lot of them) it checks for sum of every combination to be some number and then program store that combination in list. from itertools import * from math import * import Tkinter as tk import ttk x = int(raw_input('Enter number of combinations: ')) z = int(raw_input('Enter sum number: ')) def combinator(): comb = combinations(range(100), x) for i in comb: yield i my_combinations = [] combination_s = combinator() for i in combination_s: print i c = list(i) if fsum(c)==z: my_combinations.append(c) print my_combinations root = tk.Tk() root.title('ttk.Progressbar') pbar = ttk.Progressbar(root, length=300, mode='determinate', maximum = 100) pbar.pack(padx=5, pady=5) root.mainloop() I want to have ttk.progressbar that shows progress every time program evaluates sum of combinations. How can I do that? Answer: Here is an example that increases the progress bar for every combination. It just waits for a short time, but you can easily change it to do some calculations in the for loop in `ProgBarApp.start` instead of `time.sleep` from Tkinter import * from itertools import combinations import ttk import time class ProgBarApp: def __init__(self): self.vals = range(1, 20) self.combs = list(combinations(self.vals,3)) self.n = len(self.combs) self.progressbar = ttk.Progressbar(root, maximum = self.n+1) self.progressbar.pack() def start(self): for c in self.combs: self.progressbar.step() time.sleep(0.01) root.update() root.destroy() root = Tk() p = ProgBarApp() root.after(0, p.start()) root.mainloop()
What do @ and lambda mean in Python? Question: > **Possible Duplicate:** > [Understanding Python > decorators](http://stackoverflow.com/questions/739654/understanding-python- > decorators) Just trying to "port" some Python code to Java, I came then across the following python code: @fake(lambda s, t, n: [(s.field(i+1), s) for i in range(n)]) def split(secret, threshold, num_players): shares = [] for i in range(1, num_players+1): # do some shares calculation return shares There are quite some interesting constructs in this one that I never noticed before. Could anyone tell me what is the deal with this @fake thingy? def fake(replacement): """Replace a function with a fake version.""" def decorator(func): fakes = os.environ.get('FUNC_FAKE', '') if fakes == '*' or func.__name__ in fakes.split(): return replacement else: return func return decorator Further, does this lambda stand for a function name or what is the deal with that? Answer: First of all, `@fake` is a [decorator](http://stackoverflow.com/questions/739654/understanding-python- decorators). What `@fake` appears to do is to conditionally replace the function that follows, i.e. `split`, with the lambda function (note how the two take the same parameters). The decision is based on the `FUNC_FAKE` environment variable. If the latter equals `*` or contains `split` as one of its tokens, the replacement is made. Otherwise, it isn't. The fact that the replacement is a [lambda function](http://www.diveintopython.net/power_of_introspection/lambda_functions.html) is not important. It could have just as easily been made into a normal function: def split_replacement(s, t, n): return [(s.field(i+1), s) for i in range(n)]) @fake(split_replacement) def split(s, t, n): ... This whole construct is rather baffling. I struggle to come up with a reason for doing things this way, other than to try and confuse other programmers (or to play with decorators).
shorten the weekdays from texts Question: I am writing a python library that takes a paragrah that consists of different types of hours format. Paragraph is actually taken from different restaurant sites, they have hours of operation in various formats for each site. So, I decided to write a library that takes any format of (eg: M-Fri 10am - 12pm, M, Tue, Wed 00:00-18:00 etc.). My decision is to write different set of RegEx that takes a string and proceeds if it matches any of my pattern. I have choosen RegEx pattern matching because, instead of writing own logics for every pattern and replacing just using str.replace may takes a lot of time. But I stuck in regex since I am new to it. So any of you can suggest me how can I do the following task? As a first step I would like to shorten all the weekday formats to 3 letter shorten week days as below. Example: "**Monday 09:00 AM - 5:00 PM, Tuesday 09:00 AM - 5:00 PM, Wednesday 09:00 AM - 5:00 PM, Thursday 09:00 AM - 5:00 PM, Friday 09:00 AM - 5:00 PM, Saturday Closed, Sunday Closed** " Output should be "**Mon** 09:00 AM - 5:00 PM, **Tue** 09:00 AM - 5:00 PM, **Wed** 09:00 AM - 5:00 PM, **Thu** 09:00 AM - 5:00 PM, **Fri** 09:00 AM - 5:00 PM, **Sat** Closed, **Sun** Closed" Thanks. Answer: seems like a simple [`str.replace`](http://docs.python.org/2/library/stdtypes.html#str.replace) should work here: new_paragraph = paragraph.replace('Monday','Mon') You can even use the [`calendar`](http://docs.python.org/2/library/calendar.html#calendar.day_name) module to make this a little easier: import calendar for day,abbr in zip(calendar.day_name,calendar.day_abbr): paragraph = paragraph.replace(day,abbr) * * * for _really_ big paragraphs, it might be worthwhile to switch over to regex: import re import calendar regex = re.compile('|'.join(calendar.day_name)) sub_dict = dict(zip(calendar.day_name,calendar.day_abbr)) new_paragraph = regex.sub(lambda match: sub_dict[match.group(0)],paragraph) Of course, with calendar, the abbreviations/etc are locale dependent (but maybe that's desirable anyway)
Legacy Zope dynamic loading error with MySQL Question: I am in the process of moving an old installation of Zope 2 to a new Mac OS 10.8 Server. Unfortunately, our server requires Python 2.4 to run, so I have installed the MacPorts version. The server loads fine until it tries to load the MySQL-python module, at which point it dies with an `ImportError`: Traceback (most recent call last): File "/home/zope/envLRC/Zope.2.8.6/lib/python/Zope2/Startup/run.py", line 56, in ? run() File "/home/zope/envLRC/Zope.2.8.6/lib/python/Zope2/Startup/run.py", line 21, in run starter.prepare() File "/home/zope/envLRC/Zope.2.8.6/lib/python/Zope2/Startup/__init__.py", line 98, in prepare self.startZope() File "/home/zope/envLRC/Zope.2.8.6/lib/python/Zope2/Startup/__init__.py", line 257, in startZope Zope2.startup() File "/home/zope/envLRC/Zope.2.8.6/lib/python/Zope2/__init__.py", line 47, in startup _startup() File "/home/zope/envLRC/Zope.2.8.6/lib/python/Zope2/App/startup.py", line 45, in startup OFS.Application.import_products() File "/home/zope/envLRC/Zope.2.8.6/lib/python/OFS/Application.py", line 675, in import_products import_product(product_dir, product_name, raise_exc=debug_mode) File "/home/zope/envLRC/Zope.2.8.6/lib/python/OFS/Application.py", line 698, in import_product product=__import__(pname, global_dict, global_dict, silly) File "/home/zope/envLRC/Zope.2.8.6/lib/python/Products/ZMySQLDA/__init__.py", line 91, in ? import DA File "/home/zope/envLRC/Zope.2.8.6/lib/python/Products/ZMySQLDA/DA.py", line 92, in ? from db import DB File "/home/zope/envLRC/Zope.2.8.6/lib/python/Products/ZMySQLDA/db.py", line 89, in ? import _mysql File "build/bdist.macosx-10.8-x86_64/egg/_mysql.py", line 7, in ? File "build/bdist.macosx-10.8-x86_64/egg/_mysql.py", line 6, in __bootstrap__ ImportError: Inappropriate file type for dynamic loading The server is running in a virtualenv to ensure that Python 2.4 is used. Can anyone explain to me why this error is generated and what should be done about it? Thanks! Answer: It looks like something installed/created a `_mysql.py`, you should have a `_mysql.so`. If you have the `.so`, try to rename the `_mysql.py` file and restart.
How to design GUI sequence in Tkinter with Python 2.7 Question: I want to write a program that asks the user a series of questions in different dialog boxes. Each box shows up one at a time, and goes to the next box if the button next is clicked. My question is do I create a class for each Dialog and just call the next class once the button next is clicked? Or is there a more elegant solution to this? Answer: My recommendation is to build a base class that holds the current question, then when the user answers a question and advances to the next one, the base class updates the display of the new current question. You don't need to destroy widgets at any point (except when quitting the application), and you can also reuse widgets before creating new ones. Let me simplify the format of your questions to this one: each question contains a question description and a set of answers where the user can pick a single one. These simplifications can be removed, but I set them in order to present an initial code to deal with the problem. Here is a starting point for doing exactly this (my imagination towards naming was weak): import random import Tkinter import ttk # Make 5 "questions" with varied number of answers to pick from. QUESTION = [u"Question %d" % (i + 1) for i in range(5)] QOPTS = [] k = 1 for _ in QUESTION: num_opts = random.randint(3, 6) QOPTS.append([u"text %d" % (k + i) for i in range(num_opts)]) k += num_opts class Question: def __init__(self, master): self._common_var = Tkinter.StringVar() self._title = None self._lframe = None self._rb = [] self._make_gui(master) def get_answer(self): return self._common_var.get() def reset_answer(self): self._common_var.set("") def _make_gui(self, master): self._title = ttk.Label(master, padding=(0, 6, 0, 0)) self._title.grid(in_=master, padx=6, row=0, column=0, sticky='ew') self._lframe = ttk.Labelframe(master) self._lframe.grid(in_=master, padx=6, row=1, column=0, sticky='nsew') def update_gui(self, question, options): self._title['text'] = question for i, opt in enumerate(options): if i < len(self._rb): if not self._rb[i].grid_info(): self._rb[i].grid() self._rb[i]['text'] = opt else: rb = ttk.Radiobutton(self._lframe, text=opt, value=i, variable=self._common_var) rb.grid(in_=self._lframe, row=i, column=0, sticky='w') self._rb.append(rb) # Deal with i < total. for k in xrange(i + 1, len(self._rb)): self._rb[k].grid_remove() class Base: def __init__(self, frame, q, o): self.master = frame self.question = None self.curr_question = 0 self.q = q self.o = o self._make_gui(frame) self._update_gui() def next_question(self): answer = self.question.get_answer() try: answer = int(answer) except ValueError: print "Question not answered, stay here." return print "Answer for question %d: %d" % (self.curr_question, answer) self.question.reset_answer() self.curr_question += 1 self._update_gui() def _make_gui(self, frame): self.question = Question(frame) frame.columnconfigure(0, weight=1) frame.rowconfigure(1, weight=1) btn = [(u"Next", self.next_question)] self._btn = [] for i, (text, cmd) in enumerate(btn): # Assumption: the Question instance always uses the rows 0 and 1. b = ttk.Button(frame, text=text, command=cmd) b.grid(in_=frame, padx=6, pady=6, row=2, column=i, sticky='e') self._btn.append(b) def _update_gui(self): if self.curr_question == len(self.q): print "Done" self.master.quit() return elif self.curr_question == len(self.q) - 1: for btn in self._btn: # No next question btn['text'] = u"Finish" self.question.update_gui(self.q[self.curr_question], self.o[self.curr_question]) root = Tkinter.Tk() root.columnconfigure(0, weight=1) root.rowconfigure(0, weight=1) root.geometry('300x250') frame = ttk.Frame(root) frame.grid(sticky='nsew') Base(frame, QUESTION, QOPTS) root.mainloop() And here is the GUI you will get: ![enter image description here](http://i.stack.imgur.com/uIIXz.png) ![enter image description here](http://i.stack.imgur.com/IIsgB.png)
ImportError: cannot import name urandom Question: I was building a new Linux environment and seeing following error on Python. # python -c 'import random' Traceback (most recent call last): File "<string>", line 1, in <module> File "/usr/lib/python2.7/random.py", line 47, in <module> from os import urandom as _urandom ImportError: cannot import name urandom I'm not using virtualenv, so it should not be [the issue here](http://stackoverflow.com/questions/10366821/python-importerror-cannot- import-urandom-since-ubuntu-12-04-upgrade). I had compared the os.py with the file on my Ubuntu, which don't have this error. They are exactly the same, so looks like it is not [this issue](http://stackoverflow.com/questions/13545030/python-importerror-cannot- import-name-urandom) too. By checking following, it seems in my Python there is no `urandom` in `os` or `posix` # python Python 2.7.1 (r271:86832, Feb 10 2012, 16:10:22) [GCC] on linux3 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> print os.__file__ /usr/lib/python2.7/os.pyc >>> dir(os) ['EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST', 'EX_NOINPUT', 'EX_NOPERM', 'EX_NOUSER', 'EX_OK', 'EX_OSERR', 'EX_OSFILE', 'EX_PROTOCOL', 'EX_SOFTWARE', 'EX_TEMPFAIL', 'EX_UNAVAILABLE', 'EX_USAGE', 'F_OK', 'NGROUPS_MAX', 'O_APPEND', 'O_ASYNC', 'O_CREAT', 'O_DIRECT', 'O_DIRECTORY', 'O_DSYNC', 'O_EXCL', 'O_LARGEFILE', 'O_NDELAY', 'O_NOATIME', 'O_NOCTTY', 'O_NOFOLLOW', 'O_NONBLOCK', 'O_RDONLY', 'O_RDWR', 'O_RSYNC', 'O_SYNC', 'O_TRUNC', 'O_WRONLY', 'P_NOWAIT', 'P_NOWAITO', 'P_WAIT', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'UserDict', 'WCONTINUED', 'WCOREDUMP', 'WEXITSTATUS', 'WIFCONTINUED', 'WIFEXITED', 'WIFSIGNALED', 'WIFSTOPPED', 'WNOHANG', 'WSTOPSIG', 'WTERMSIG', 'WUNTRACED', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_copy_reg', '_execvpe', '_exists', '_exit', '_get_exports_list', '_make_stat_result', '_make_statvfs_result', '_pickle_stat_result', '_pickle_statvfs_result', '_spawnvef', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'chown', 'chroot', 'close', 'closerange', 'confstr', 'confstr_names', 'ctermid', 'curdir', 'defpath', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fchdir', 'fchmod', 'fchown', 'fdatasync', 'fdopen', 'fork', 'forkpty', 'fpathconf', 'fstat', 'fstatvfs', 'fsync', 'ftruncate', 'getcwd', 'getcwdu', 'getegid', 'getenv', 'geteuid', 'getgid', 'getgroups', 'getloadavg', 'getlogin', 'getpgid', 'getpgrp', 'getpid', 'getppid', 'getresgid', 'getresuid', 'getsid', 'getuid', 'initgroups', 'isatty', 'kill', 'killpg', 'lchown', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'major', 'makedev', 'makedirs', 'minor', 'mkdir', 'mkfifo', 'mknod', 'name', 'nice', 'open', 'openpty', 'pardir', 'path', 'pathconf', 'pathconf_names', 'pathsep', 'pipe', 'popen', 'popen2', 'popen3', 'popen4', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'rmdir', 'sep', 'setegid', 'seteuid', 'setgid', 'setgroups', 'setpgid', 'setpgrp', 'setregid', 'setresgid', 'setresuid', 'setreuid', 'setsid', 'setuid', 'spawnl', 'spawnle', 'spawnlp', 'spawnlpe', 'spawnv', 'spawnve', 'spawnvp', 'spawnvpe', 'stat', 'stat_float_times', 'stat_result', 'statvfs', 'statvfs_result', 'strerror', 'symlink', 'sys', 'sysconf', 'sysconf_names', 'system', 'tcgetpgrp', 'tcsetpgrp', 'tempnam', 'times', 'tmpfile', 'tmpnam', 'ttyname', 'umask', 'uname', 'unlink', 'unsetenv', 'utime', 'wait', 'wait3', 'wait4', 'waitpid', 'walk', 'write'] >>> import posix >>> dir(posix) ['EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST', 'EX_NOINPUT', 'EX_NOPERM', 'EX_NOUSER', 'EX_OK', 'EX_OSERR', 'EX_OSFILE', 'EX_PROTOCOL', 'EX_SOFTWARE', 'EX_TEMPFAIL', 'EX_UNAVAILABLE', 'EX_USAGE', 'F_OK', 'NGROUPS_MAX', 'O_APPEND', 'O_ASYNC', 'O_CREAT', 'O_DIRECT', 'O_DIRECTORY', 'O_DSYNC', 'O_EXCL', 'O_LARGEFILE', 'O_NDELAY', 'O_NOATIME', 'O_NOCTTY', 'O_NOFOLLOW', 'O_NONBLOCK', 'O_RDONLY', 'O_RDWR', 'O_RSYNC', 'O_SYNC', 'O_TRUNC', 'O_WRONLY', 'R_OK', 'TMP_MAX', 'WCONTINUED', 'WCOREDUMP', 'WEXITSTATUS', 'WIFCONTINUED', 'WIFEXITED', 'WIFSIGNALED', 'WIFSTOPPED', 'WNOHANG', 'WSTOPSIG', 'WTERMSIG', 'WUNTRACED', 'W_OK', 'X_OK', '__doc__', '__name__', '__package__', '_exit', 'abort', 'access', 'chdir', 'chmod', 'chown', 'chroot', 'close', 'closerange', 'confstr', 'confstr_names', 'ctermid', 'dup', 'dup2', 'environ', 'error', 'execv', 'execve', 'fchdir', 'fchmod', 'fchown', 'fdatasync', 'fdopen', 'fork', 'forkpty', 'fpathconf', 'fstat', 'fstatvfs', 'fsync', 'ftruncate', 'getcwd', 'getcwdu', 'getegid', 'geteuid', 'getgid', 'getgroups', 'getloadavg', 'getlogin', 'getpgid', 'getpgrp', 'getpid', 'getppid', 'getresgid', 'getresuid', 'getsid', 'getuid', 'initgroups', 'isatty', 'kill', 'killpg', 'lchown', 'link', 'listdir', 'lseek', 'lstat', 'major', 'makedev', 'minor', 'mkdir', 'mkfifo', 'mknod', 'nice', 'open', 'openpty', 'pathconf', 'pathconf_names', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'rename', 'rmdir', 'setegid', 'seteuid', 'setgid', 'setgroups', 'setpgid', 'setpgrp', 'setregid', 'setresgid', 'setresuid', 'setreuid', 'setsid', 'setuid', 'stat', 'stat_float_times', 'stat_result', 'statvfs', 'statvfs_result', 'strerror', 'symlink', 'sysconf', 'sysconf_names', 'system', 'tcgetpgrp', 'tcsetpgrp', 'tempnam', 'times', 'tmpfile', 'tmpnam', 'ttyname', 'umask', 'uname', 'unlink', 'unsetenv', 'utime', 'wait', 'wait3', 'wait4', 'waitpid', 'write'] Here is what I had on my Linux. # rpm -qa|grep python python-base-2.7.1-4.21.i586 python-xml-2.7.1-4.21.i586 dbus-python-0.83.1-3.2.i586 libpython-2.7.1-4.21.i586 python-2.7.3-6.18.i686 # # ls -l /dev/urandom crw-rw-rw- 1 root root 1, 9 Dec 12 22:16 /dev/urandom Am I missing any Python modules? Answer: The `urandom` in `os` changed between 2.7.1 (your version) and 2.7.3 (current). On 2.7.1 posix does not have a urandom and os.py has a fallback method (at the end of `os.py`). In 2.7.3 posix always has a urandom function. So maybe you're mixing os.py versions?
Python smtplib sometimes fails sending Question: I wrote a simple "POP3S to Secure SMTP over TLS" MRA script in Python (see below). It works fine, but sometimes it returns "Connection unexpectedly closed" while trying to send via SMTP. Running the script again will deliver that message successfully. Please give me some suggestions why it would fail to deliver a message sometimes but at the next run it delivers exactly this message successfully!? #! /usr/bin/env python import poplib import email def forward_pop3_smtp( smtp_credentials, pop3_credentials, forward_address): pop3_server = pop3_credentials[0] pop3_port = pop3_credentials[1] pop3_user = pop3_credentials[2] pop3_password = pop3_credentials[3] message_recipient = forward_address server = poplib.POP3_SSL( pop3_server, pop3_port) server.user( pop3_user) server.pass_( pop3_password) for messages_iterator in range( len( server.list()[1])): message_list = server.retr( messages_iterator + 1)[1] message_string = '' for message_line in message_list: message_string += message_line + '\n' message_message = email.message_from_string( message_string) message_message_as_string = message_message.as_string() message_sender = message_message[ 'From'] print( 'message_sender = ' + message_sender) smtp_return = send_smtp( smtp_credentials, message_sender, message_recipient, message_message_as_string) print( 'smtp_return = ' + str(smtp_return)) if smtp_return == 0: print( 'Deleting message ' + message_message[ 'Subject'] + ':\n') return_delete = server.dele( messages_iterator + 1) print( 'return_delete = \n' + str(return_delete)) print( '\n') server.quit() def send_smtp( smtp_credentials, message_sender, message_recipient, message_message_as_string): smtp_server = smtp_credentials[0] smtp_port = smtp_credentials[1] smtp_user = smtp_credentials[2] smtp_password = smtp_credentials[3] import smtplib exception = 0 try: server = smtplib.SMTP( smtp_server) server.starttls() server.login( smtp_user, smtp_password) smtp_sendmail_return = server.sendmail( message_sender, message_recipient, message_message_as_string) server.quit() except Exception, e: exception = 'SMTP Exception:\n' + str( e) + '\n' + str( smtp_sendmail_return) return exception if __name__ == '__main_': print( 'This module needs to be imported!\n') quit() Answer: Use Port 587 for TLS. I don't see the script use smtp_port Use like, server = smtplib.SMTP( smtp_server, int(smtp_port) For Secure SMTP (SMTP + SSL), use smtplib.SMTP_SSL
How to share data between processes in Python using MPI? Question: I'm attempting to parallelize a script I wrote. Each process needs to do a calculation and store the data to a specific part of an array (list of lists). Each process is calculating and storing its data alright, but I can't figure out how to get the data from the non-root processes to the root process so that it can print the data out to file. I created a minimum working example of my script---this one is designed to run on 2 cores only for simplicity: from mpi4py import MPI import pdb import os comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() # Declare the array that will store all the temp results temps = [[0 for x in xrange(5)] for x in xrange(4)] # Loop over all directories if rank==0: counter = 0 for i in range(2): for j in range(5): temps[i][j] = counter counter = counter + 1 else: counter = 20 for i in range(2,4): for j in range(5): temps[i][j] = counter counter = counter + 1 temps = comm.bcast(temps,root=0) if rank==0: print temps I execute the script using: mpiexec -n 2 python mne.py When the case finishes, the output is: [0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] So you can see that the data sharing is not working as I want. Can someone please show me the correct way to get data back to the root process? Answer: The code is working correctly, just not doing what you'd like. This line temps = comm.bcast(temps,root=0) broadcasts processor 0's `temps` variable to all processors (including rank 0), which of course gives exactly the results above. You want to use `gather` (or `allgather`, if you want all of the processors to have the answer). That would look something more like this: from mpi4py import MPI import pdb import os comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() assert size == 2 # Declare the array that will store all the temp results temps = [[0 for x in xrange(5)] for x in xrange(4)] # declare the array that holds the local results locals =[[0 for x in xrange(5)] for x in xrange(2)] # Loop over all directories if rank==0: counter = 0 for i in range(2): for j in range(5): locals[i][j] = counter counter = counter + 1 else: counter = 20 for i in range(2): for j in range(5): locals[i][j] = counter counter = counter + 1 temps = comm.gather(locals,temps,root=0) if rank==0: print temps If you really want to do the collection in-place, and you know (say) that all the real data is going to be larger than the zero you've initialized the data with, you can use a reduction operation, but that goes easier with numpy arrays: from mpi4py import MPI import numpy comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() assert size == 2 # Declare the array that will store all the temp results temps = numpy.zeros((4,5)) # Loop over all directories if rank==0: counter = 0 for i in range(2): for j in range(5): temps[i,j] = counter counter = counter + 1 else: counter = 20 for i in range(2,4): for j in range(5): temps[i,j] = counter counter = counter + 1 comm.Allreduce(MPI.IN_PLACE,temps,op=MPI.MAX) if rank==0: print temps
Unresolved import PyDev/IronPython Question: I have both Aptana Studio 3 and Eclipse 4.2.1 (w/ PyDev & PyDev extensions) installed on Windows XP (SP3) systems. I have been unsuccesful in loading external .NET assemblies. Given the assembly myassembly.dll containing a namespace `myNameSpace`, I set up a new project with the IronPython interpreter selected. In the src folder of my project I make a Python file 'Test.py' containing 3 statements: import clr clr.AddReferenceToFile('myassembly.dll') import myNameSpace I always get an unresolved import on the 3rd statement with both Aptana Studio and Eclipse 1. I have modified the 2nd statement to use `clr.AddReferenceToFileAndPath('Fully qualified path and file name')` 2. I have also tried adding the path to an external library and placing my assembly in that library with the same results. The 3 statements execute fine from the IronPython console. Also, imports of .NET System and other modules work OK. But presumably these modules are registered in the GAC. This seems to be unique to the IronPython interpreter and the final `PYTHONPATH`. I have path references to the project src folder and to an external source folder, both of which contain the assembly. What am I missing here? Answer: I haven't actually tested it, but this is usually the case for the forced builtins (see the forced builtins section at <http://pydev.org/manual_101_interpreter.html>). Still, it won't do the: import clr clr.AddReferenceToFile('myassembly.dll') So, if that't really required, you may edit the file: eclipse\plugins\org.python.pydev_XXX\pysrc\pycompletionserver.py and add that code (before the if sys.platform == "darwin") for the import to work in the forced builtins.
Run multiple find and replaces in Python (on every file in the folder and sub-folder) Question: I have a folder (courses) with sub-folders and a random number of files. I want to run multiple search and replaces on those random files. Is it possible to do a wild card search for `.html` and have the replaces run on every html file ? Search and replaces: * 1) `"</b>"` to `"</strong>"` * 2) `"</a>"` to `"</h>"` * 3) `"<p>"` to `"</p>"` * Also all these replaces have to be run on every file in the folder and sub-folders. Thank you so much Answer: Try this, import os from os.path import walk mydict = {"</b>":"</strong>", "</a>":"</h>", "<p>":"</p>"} for (path, dirs, files) in os.walk('./'): for f in files: if f.endswith('.html'): filepath = os.path.join(path,f) s = open(filepath).read() for k, v in mydict.iteritems(): s = s.replace(k, v) f = open(filepath, 'w') f.write(s) f.close() You can change `os.walk('./')` to `os.walk('/anyFolder/')`
call linux command within python Question: > **Possible Duplicate:** > [Equivalent of Backticks in > Python](http://stackoverflow.com/questions/1410976/equivalent-of-backticks- > in-python) I am looking for the best way to run a terminal command (ls -l) within Python. I have read about subprocess but I do not understand it fully, if someone could try and make me understand what is happening I would be grateful. I need to use the ls -l command to retrieve a hard link number which is != 1 and then save this number to match it against a directory number elsewhere. For now I would just like to know how to grab the hard link number and save it to a variable using subprocess (or a better method if there is one). Here is the code I have used so far: #!/usr/bin/python #tool that resolves time machine directories import os #create output file os.chdir("/home/sean/Desktop") hard_link_number = open('hardLinkNumber.log', 'w') #move into mounted backup (figure out how to remove xe2 etc) os.chdir("/mnt/Backups.backupdb/stuart dent\xe2\x80\x99s MacBook Pro/2010-08-10-160859/MAc") #find hard link data print>>hard_link_number, os.system("ls -la") hard_link_number.close() os.system("ls -la") outputs the information I require but it will not save it to the file I have created. I read elsewhere that os.system will not output data. Answer: You want [`os.stat`](http://docs.python.org/2/library/os.html#os.stat) (specifically the `st_nlink` attribute). _Edit:_ To paraphrase [jwz](http://www.jwz.org/): Some people, when confronted with a problem, think "I know, I'll parse the output of `ls -l`." Now they have two problems.
How to convert string date interval to number of days or seconds (ISO_8601)? Question: Is there an easy way in python to transform a string representation of a date interval: P1M To a timestamp or a datetime object? Basically I need to work with date intervals according to this ISO: <http://en.wikipedia.org/wiki/ISO_8601> Something similar to <http://php.net/manual/en/class.dateinterval.php> Answer: There appears to be a third-party module called [isodate](http://pypi.python.org/pypi/isodate/) that may do what you want: In [1]: from isodate import parse_duration In [2]: parse_duration('P1M') Out[2]: isodate.duration.Duration(0, 0, 0, years=0, months=1) You can also convert this object into a `datetime.timedelta` object if necessary (providing a `start` or `end` parameter so that the proper duration can be calculated in terms of the provided date): In [8]: import datetime In [9]: d = parse_duration('P1M') In [10]: d.todatetime(start=datetime.datetime.today()) Out[10]: datetime.timedelta(31)
Google app engine + python (django) deployment error: Error loading MySQLdb module Question: I am creating an app on Google App Engine. I am using Django 1.4 and Python 2.7. Everything works fine on localhost. But after deployment it is not running, I keep getting this on admin logs: 2012-12-15 15:02:41.870 /base/python27_runtime/python27_lib/versions/1/lib/cacerts/urlfetch_cacerts.txt missing; without this urlfetch will not be able to validate SSL certificates. W 2012-12-15 15:02:41.870 No ssl package found. urlfetch will not be able to validate SSL certificates. E 2012-12-15 15:02:46.086 Traceback (most recent call last): File "/base/python27_runtime/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 196, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "/base/python27_runtime/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 266, in _LoadHandler __import__(cumulative_path) File "/base/data/home/apps/s~cloudwallforever/1.363864476397206865/djangoappengine/main/__init__.py", line 28, in <module> setup_env() File "/base/data/home/apps/s~cloudwallforever/1.363864476397206865/djangoappengine/boot.py", line 82, in setup_env setup_logging() File "/base/data/home/apps/s~cloudwallforever/1.363864476397206865/djangoappengine/boot.py", line 130, in setup_logging if not settings.DEBUG: File "/base/data/home/apps/s~cloudwallforever/1.363864476397206865/django/utils/functional.py", line 276, in __getattr__ self._setup() File "/base/data/home/apps/s~cloudwallforever/1.363864476397206865/django/conf/__init__.py", line 42, in _setup self._wrapped = Settings(settings_module) File "/base/data/home/apps/s~cloudwallforever/1.363864476397206865/django/conf/__init__.py", line 87, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/base/data/home/apps/s~cloudwallforever/1.363864476397206865/django/utils/importlib.py", line 35, in import_module __import__(name) File "/base/data/home/apps/s~cloudwallforever/1.363864476397206865/settings.py", line 6, in <module> import django.db.backends.mysql.base File "/base/data/home/apps/s~cloudwallforever/1.363864476397206865/django/db/backends/mysql/base.py", line 14, in <module> raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb Any ideas why it is happening? Answer: The 'Django Support' documentation hints at the solution, but doesn't make it explicit: > Since the standard django.db.backends.mysql backend uses MySQLdb internally, > app.yaml must reference MySQLdb in the list of libraries. Adding the following to `app.yaml` seems to fix the ImportError: libraries: - name: MySQLdb version: "latest" Note that MySQLdb is not currently included in the list of [available third party libraries](https://developers.google.com/appengine/docs/python/tools/libraries27). I tried it on a whim and it seems to have fixed the issue for me, YMMV.[enter link description here](https://developers.google.com/appengine/docs/python/cloud-sql/django)
sqrt function weird behaviour in Python Question: In Python, I wrote a custom code sqrt(x, delta) to calculate the square root of a given number with a delta-close approximation. It uses a while loop and a binary-search-like algorithm. The code: from __future__ import division def sqrt(x, delta): start = 0 end = x while (end-start) > delta: middle = (start + end) / 2 middle_2 = middle * middle if middle_2 < x: start = middle print "too low" elif middle_2 > x: end = middle print "too high" else: return middle result = (start + end) / 2 return result It basicly works and it is quite fast, but there are cases when it gets into an infinite while-loop. Examples: sqrt(1e27, 1/1024) => works fine (returns 'too low's and 'too high's, then returns correct result) sqrt(1e28, 1/1024) => works fine sqrt(1e29, 1/1024) => never-ending loop, it keeps printing 'too low' forever sqrt(1e30, 1/1024) => works fine sqrt(1e31, 1/1024) => 'too low' forever sqrt(1e32, 1/1024) => works fine sqrt(1e33, 1/1024) => works fine (also surprising after the problem with 1e29 and 1e31) sqrt(1e34, 1/1024) => works fine sqrt(1e35, 1/1024) => 'too low' forever sqrt(1e36, 1/1024) => works fine sqrt(1e37, 1/1024) => 'too high' forever (too high this time!) sqrt(1e38, 1/1024) => works fine sqrt(1e39, 1/1024) => works fine (surprising again..) ... 1e40-1e45 ... they all work fine sqrt(1e46, 1/1024) => 'too low' forever (surprisingly it occurs now with 1e'even number') ... sqrt(1e200, 1/1024) => works fine sqrt(1e201, 1/1024) => works fine ... sqrt(1e299, 1/1024) => 'too low' forever sqrt(1e300, 1/1024) => 'too high' forever ... sqrt(1e304, 1/1024) => 'too high' forever sqrt(1e305, 1/1024) => works fine ... 305-308 ... they allwork fine sqrt(1e309, 1/1024) => inf (reached some 'infinite' limit?) I first thought it was with numbers above a limit, like 1e20.. But then it worked with them as well. Also, I had this thought that is was about 1e'odd' or 1e'even' numbers, but as we can see in the examples, it wasn't that. I also tried it using different delta's instead 1/1024, but they showed similar behavior. I would appreciate any explanation that tells what is going on behind the scenes that causes this behavior. Answer: `float` can only represent a finite set of numbers. Your code ends up in a situation where `start` and `end` are two consecutive such numbers. As a result, `(start + end) / 2` has to be either rounded down to `start` or rounded up to `end`. If it gets rounded down, `middle_2 < x`. Now, if `end - start > delta`, you've got a "too low" infinite loop. If it gets rounded up, and if `end - start > delta`, you've got a "too high" infinite loop. You should probably redefine `delta` as a relative error rather than an absolute one.
How to make a python decorator function in Flask with arguments (for authorization) Question: I used a flask snippet for my flask-login that checks that a user is logged in: from functools import wraps def logged_in(f): @wraps(f) def decorated_function(*args, **kwargs): if session.get('logged_in') is not None: return f(*args, **kwargs) else: flash('Please log in first.', 'error') return redirect(url_for('login')) return decorated_function And I decorate views like so: @app.route('/secrets', methods=['GET', 'POST']) @logged_in def secrets(): error = None I'd like to do something similar for authorization, too. Right now, I have many views to check that a user owns a resource, let's say the `hotdogs` resource. If the logged_in user is the owner of that particular hotdog, he can edit and manage his hotdogs. If he isn't, I kick him out to the unauthorized screen. @app.route('/<hotdog>/addmustard/',methods=["GET"]) @logged_in def addmustard(hotdog): if not (authorizeowner(hotdog)): return redirect(url_for('unauthorized')) do_stuff() `authorizeowner()` takes a hotdog as input and checks that the recorded hotdog owner matches the owner name listed in the session variable. I tried making a owns_hotdog wrapper/decorator function similar to my logged in one, but it complained that it didn't accept arguments. How can I achieve something similar? Something like... def owns_hotdog(f): @wraps(f) def decorated_function(*args, **kwargs): if not authorizeowner(hotdog): return f(*args, **kwargs) else: flash('Please log in first.', 'error') return redirect(url_for('login')) return decorated_function From the error message, decorator seems not to be receiving the hotdog argument that Flask views have access to from the variable in the route. My hope is for something like... @app.route('/<hotdog>/addmustard/',methods=["GET"]) @logged_in @owns_hotdog(hotdog) def addmustard(hotdog): do_stuff() Everything works with my current authorizeowner(hotdog) function, but it just seems cleaner to have this in place as a wrapper on top of my route, rather than as the first line inside the route. Some other notes: * I know that Flask-Security and Flask-Principal can manage authorization for me. Unfortunately, I'm using an unsupported database back-end and am unable to use these extensions. So, I'm forced to do authentication without them. * If you see any glaring holes in doing authorization this way, please let me know! Answer: Here's how to do it: from functools import update_wrapper def owns_hotdog(hotdog): def decorator(fn): def wrapped_function(*args, **kwargs): # First check if user is authenticated. if not logged_in(): return redirect(url_for('login')) # For authorization error it is better to return status code 403 # and handle it in errorhandler separately, because the user could # be already authenticated, but lack the privileges. if not authorizeowner(hotdog): abort(403) return fn(*args, **kwargs) return update_wrapper(wrapped_function, fn) return decorator @app.errorhandler(403) def forbidden_403(exception): return 'No hotdogs for you!', 403 When decorator takes arguments, it's not really a decorator, but a _factory_ function which returns the _real_ decorator. But if I were you, I would use Flask-Login for authentication and augment it with custom decorators and functions as yours to handle authorization. I looked into Flask-Principal, but found it overly complicated for my tastes. Haven't checked Flask-Security, but I believe it uses Flask-Principal for authorization. Overall I think that Flask-Login with some custom code is enough most of the time.
what regex expression in python for this text Question: I have a complicated text file, here is part of it: & \multirow{2}{*}{52.7} & \multirow{2}{*}{3} & \multirow{2}{*}{$<$ 0.001}\\ I'm interested in the numbers after the `{*}`. Here is what I tried with no luck: import re m = re.findall(r'{\*}{(.+)}', '& \multirow{2}{*}{52.7} & \multirow{2}{*}{3} & \multirow{2}{*} $<$ 0.001}\\') However, I get the following result: ['52.7} & \\multirow{2}{*}{3} & \\multirow{2}{*}{$<$ 0.001'] I tried many other combinations but I either get the first number (e.g 52.7), or the middle number (3) or the above. How can I get `52.7, 3, $<$ 0.001` in a group (list). Answer: That's because by default `+` and `*` operators are greedy. Use non-greedy modification instead: {\*}{(.+?)} Reference: <http://www.regular-expressions.info/repeat.html> ("_Watch Out for The Greediness!_ " section)
Python plugins like Minecraft Bukkit Question: I've been reading this: <http://lkubuntu.wordpress.com/2012/10/02/writing-a-python-plugin-api/> I'm trying to do something like Minecraft help system. Let's say I have my main module, and the help commands are: > help > test1 > test2 > And then, after loading the plugin, I would have the same set, plus the ones that the plugin has available. Also, when processing the commands, how can I do, to distinguish the ones from internal program to the ones from plugins?! So far, I've come up with this: import imp import os PluginFolder = "./plugins" MainModule = "__init__" def getPlugins(): plugins = [] possibleplugins = os.listdir(PluginFolder) for i in possibleplugins: location = os.path.join(PluginFolder,i) if not os.path.isdir(location) or not MainModule + ".py" in os.listdir(location): continue info = imp.find_module(MainModule, [location]) plugins.append({"name":i, "info": info}) return plugins def loadPlugin(plugin): return imp.load_module(MainModule, *plugin["info"]) disponiveis = [] for i in getPlugins(): print("Loading plugin "+ i["name"]) plugin = loadPlugin(i) plugin.run() disponiveis.append(i["name"]) while 1: foo = raw_input(":") if foo == 'quit': break; elif foo in disponiveis: print "ok" else: continue Not much from the original example :| My BIG problem is that cycle where it loads all the plugins. Currently I have 2 plugins, _hello_ and _testing_. How can I do to have something like this: send_command(plugin_name, action) Also, the if/elif is kinda lame... Available commands should come from the plugin. Using a _dict_ maybe?!?! And then when loading the plugin, it would add the aditional commands to that dict ?!?! Answer: As the last line of the blog entry you cite says "Now, of course, this plugin API is very simple, and can easily (and should) be extended for your program’s needs." The only "api" defined in the sample code is a `plugin.run()` method that doesn't return anything. So at the very least from your question it sounds like you need one the describes the available "commands" the loaded plugin has. One way to do that would be to define another method that all plugins must provide called `available_commands()` which returns a dictionary of commands where the keys are all command names and the values are corresponding functions that do them. However that could need to be extended with some mechanism to provide command argument information back to the client application as well. How this might be done is limited only by your imagination to either invent something yourself or perhaps learn how others have done it, perhaps by asking a more specific question here on StackOverflow.
Python NoneType error in some executions of a program Question: I was testing a code found in a book about Genetic Algorithms and I came up with an strange mistake. The code is the following: import time import random import math people = [('Seymour','BOS'), ('Franny','DAL'), ('Zooey','CAK'), ('Walt','MIA'), ('Buddy','ORD'), ('Les','OMA')] # Laguardia destination='LGA' flights={} # for line in file('schedule.txt'): origin,dest,depart,arrive,price=line.strip().split(',') flights.setdefault((origin,dest),[]) # Add details to the list of possible flights flights[(origin,dest)].append((depart,arrive,int(price))) def getminutes(t): x=time.strptime(t,'%H:%M') return x[3]*60+x[4] def printschedule(r): for d in range(len(r)/2): name=people[d][0] origin=people[d][1] out=flights[(origin,destination)][int(r[d])] ret=flights[(destination,origin)][int(r[d+1])] print '%10s%10s %5s-%5s $%3s %5s-%5s $%3s' % (name,origin, out[0],out[1],out[2], ret[0],ret[1],ret[2]) def schedulecost(sol): totalprice=0 latestarrival=0 earliestdep=24*60 for d in range(len(sol)/2): # Get the inbound and outbound flights origin=people[d][1] outbound=flights[(origin,destination)][int(sol[d])] returnf=flights[(destination,origin)][int(sol[d+1])] # Total price is the price of all outbound and return flights totalprice+=outbound[2] totalprice+=returnf[2] # Track the latest arrival and earliest departure if latestarrival<getminutes(outbound[1]): latestarrival=getminutes(outbound[1]) if earliestdep>getminutes(returnf[0]): earliestdep=getminutes(returnf[0]) # Every person must wait at the airport until the latest person arrives. # They also must arrive at the same time and wait for their flights. totalwait=0 for d in range(len(sol)/2): origin=people[d][1] outbound=flights[(origin,destination)][int(sol[d])] returnf=flights[(destination,origin)][int(sol[d+1])] totalwait+=latestarrival-getminutes(outbound[1]) totalwait+=getminutes(returnf[0])-earliestdep # Does this solution require an extra day of car rental? That'll be $50! if latestarrival>earliestdep: totalprice+=50 return totalprice+totalwait def geneticoptimize(domain,costf,popsize=50,step=1, mutprob=0.2,elite=0.2,maxiter=100): # Mutation Operation def mutate(vec): i=random.randint(0,len(domain)-1) if random.random()<0.5 and vec[i]>domain[i][0]: return vec[0:i]+[vec[i]-step]+vec[i+1:] elif vec[i]<domain[i][1]: return vec[0:i]+[vec[i]+step]+vec[i+1:] # Crossover Operation def crossover(r1,r2): i=random.randint(1,len(domain)-2) return r1[0:i]+r2[i:] # Build the initial population pop=[] for i in range(popsize): vec=[random.randint(domain[i][0],domain[i][1]) for i in range(len(domain))] pop.append(vec) # How many winners from each generation? topelite=int(elite*popsize) # Main loop for i in range(maxiter): scores=[(costf(v),v) for v in pop] scores.sort() ranked=[v for (s,v) in scores] # Start with the pure winners pop=ranked[0:topelite] # Add mutated and bred forms of the winners while len(pop)<popsize: if random.random()<mutprob: # Mutation c=random.randint(0,topelite) pop.append(mutate(ranked[c])) else: # Crossover c1=random.randint(0,topelite) c2=random.randint(0,topelite) pop.append(crossover(ranked[c1],ranked[c2])) # Print current best score print scores[0][0] return scores[0][1] This code uses a .txt file called schedule.txt and that it can be downloaded from <http://kiwitobes.com/optimize/schedule.txt> When I run the code I put the following, according to the book: >>> domain=[(0,8)]*(len(optimization.people)*2) >>> s=optimization.geneticoptimize(domain,optimization.schedulecost) But the error that I get is: Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> s=optimization.geneticoptimize(domain,optimization.schedulecost) File "optimization.py", line 99, in geneticoptimize scores=[(costf(v),v) for v in pop] File "optimization.py", line 42, in schedulecost for d in range(len(sol)/2): TypeError: object of type 'NoneType' has no len() The thing is that the error message appears sometimes and other times not. I have checked the code and I cannot see where it can be the fault, because pop never is populated with empty vectors. Any help? Thanks Answer: You can get `None` in your `pop` list if neither of the conditions in the `mutate` function are met. In that case the control runs off the end of the function, which is the same as returning `None`. You need to update the code to either have only one condition, or to handle a case that doesn't meet either of them in a separate block: def mutate(vec): i=random.randint(0,len(domain)-1) if random.random()<0.5 and vec[i]>domain[i][0]: return vec[0:i]+[vec[i]-step]+vec[i+1:] elif vec[i]<domain[i][1]: return vec[0:i]+[vec[i]+step]+vec[i+1:] else: # new code needed here!
Insert statement MySQL via python Question: I am trying to make a python script that adds a video url and time to my videopost table in DB. This is my 3rd script at python. I am still learning. Also please tell me how to lower the execution time of this script. Code: #!/usr/bin/python import MySQLdb import sys db = MySQLdb.connect (host = "host.com", user="myusername",passwd="pass", db = "dbname") cursor = db.cursor () db.query("SELECT now()") result = db.use_result() time= str("%s" % \ result.fetch_row()[0]) print time db.close() cursor =db.cursor() vidurl = raw_input("Enter the URL to the video:") print vidurl cursor.execute ("""INSERT INTO videopost(vidurl, time) VALUES (%s, %s)""", (vidurl,time)) db.commit() db.close() The error i am getting in this is File "vidup.py", line 28, in <module> cursor.execute ("""INSERT INTO videopost(vidurl, time) VALUES (%s, %s)""", (vidurl,time)) File "/usr/local/lib/python2.6/site-packages/MySQL_python-1.2.3-py2.6-freebsd-8.2-RELEASE-amd64.egg/MySQLdb/cursors.py", line 155, in execute _mysql_exceptions.InterfaceError: (0, '') Well thanks for the help. For people looking for solution i am posting the correction below: cursor.execute("SELECT now()") result = cursor.fetchall() time= str("%s" % \ result[0]) print time vidurl = raw_input("Enter the URL to the video:") print vidurl Answer: You are closing the connection and then trying to grab a cursor: db.close() cursor =db.cursor() Remove the first line and everything should work.
How do I configure my system so that Windows Python 2.7 CGI scripts see user-defined packages? Question: I have a Python script that uses some of my own packages in my own library which is stored in a non-standard folder: k:\lib. When running the script from the command-line the interpreter can find my packages because I have set the PYTHONPATH environment variable. However, when running the script as a CGI script, the environment variable does not seem to be read, so my question is what can I do about this? One solution I read was to put import sys sys.path.append( 'k:\\lib' ) at the top of my script but this doesn't work - the next line in my script is import site_consts where site_consts is in k:\lib but I get the error message "no module named site_consts". Not sure if this is Python problem or a Windows or an Apache one. Answer: You could add a `name.pth` file to one of the four directories described [here](http://docs.python.org/2/library/site.html#module-site) in the documentation.
How to select two elements from list and do math on them in Python? Question: I have a file containing several start and end-positions of a sequence (MANY!) and I want to select the start and end positions, subtract the end position from the start to get the length of a particular sequence, and then randomly place that sequence somewhere between the smallest start number and largest end number. Don't know if that makes any sense..... However here is what I have so far: #!/usr/bin/env python import sys import random import math import re file = open(sys.argv[1], 'r') list = [] for line in file: if line.startswith('G'): continue else: pos = re.split('\s', line) list.append(pos[0]) list.append(pos[1]) list = map(int, list) for i in list: #ldom = (i:i+1)-i + 1 print randrange(1, 3000000000, ldom) file.close() The '#' line is the one I'm having problems with. I have a list where each element represents either a start or end position, list[0] represents a start and list[1] an end position. I just don't know how to subtract list[1] from list[0], and add 1 to that number....list comprehensions only seem to work on non-specific elements or all. Answer: Here's an ipython-interpreter example of splitting a line on whitespace (as noted in docs for [str.split()](http://docs.python.org/2/library/stdtypes.html#str.split), whitespace is the default separator), converting items to integers (via `map(int, ...)`, and then [zipping](http://docs.python.org/2/library/functions.html#zip) into pairs: In [127]: line='0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16' In [128]: zip(*[iter(map(int, line.split()))]*2) Out[128]: [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11), (12, 13), (14, 15)] You can set some variable, say `bounds`, to the zip expression, and then iterate on list `bounds` to do whatever it is you need to do to the “particular sequence”. For example: In [131]: bounds = zip(*[iter(map(int, line.split()))]*2) In [132]: for lo, hi in bounds: print 'lo:', lo, '\thi:', hi, '\tdelta:', hi-lo+1 lo: 0 hi: 1 delta: 2 lo: 2 hi: 3 delta: 2 lo: 4 hi: 5 delta: 2 lo: 6 hi: 7 delta: 2 lo: 8 hi: 9 delta: 2 lo: 10 hi: 11 delta: 2 lo: 12 hi: 13 delta: 2 lo: 14 hi: 15 delta: 2
How do I upload a pdf from a Django HTTP object to google drive Question: I use pisa to create pdf documents to render to the user: response = HttpResponse() pisa.CreatePDF(src=html, dest=response, show_error_as_pdf=True) return response response.content contains the pdf. I've used the dropbox-python sdk to do this: dropbox_client.put_file(folder_path, response.content) It seems to understand response.content as a pdf and uploads the file correctly I need to do the same thing with the google-drive-python-api. This reference (https://developers.google.com/drive/v2/reference/files/insert) shows a basic method, but MediaFileUpload seems to look for a physical file. There is MediaIoBaseUpload also but it doesn't seem to accept response.content. I'm not very familiar with file/i/o stuff, so I listed everything from django to dropbox to G-Drive here, hoping it would clarify my use; hopefully I didn't confuse matters. Answer: The `apiclient.http` file from the python Google API toolkit, contains the `MediaIoBaseUpload` object that does exactly what you need. Only that it expects a file handle or something that behaves like file handle (the `fh` parameter). You're in luck: that's exactly what the [`StringIO`](http://docs.python.org/2/library/stringio.html) module is for: import StringIO # You could try importing cStringIO which gives better performance fh = StringIO.StringIO(response.content) media = MediaIoBaseUpload(fh, mimetype='some/mimetype') # See https://developers.google.com/drive/v2/reference/files/insert for the rest * * * `MediaInMemoryUpload` would do the trick too, but it's deprecated now.
Separate a csv for processing Question: I am new to Python and love it. However, I have a problem and hope someone can help. I have a string of values separated by commas and want to use a loop to individually process each of the values in turn. e.g. string = '1,2,3,4,5,6,' I want to take the first value '1' and process it before moving on to the next value. Answer: In the case above, you can use the `split` method to split a string by commas and then iterate through the resulting list: In [1]: s = '1,2,3,4,5,6,' In [2]: s.split(',') Out[2]: ['1', '2', '3', '4', '5', '6', ''] In [3]: for i in s.split(','): ...: if i: ...: print i ...: ...: 1 2 3 4 5 6 `split` returns a list, so what we do here is iterate through the resulting list and then check to see if the field is empty or not; it not process. We do this check because your string ends in a `,`, which as you can see returns an empty string. Also note that this splits on **all** commas - not just those that separate values. For the case above, that should be fine, but in the case where you want to do more advanced handling of CSV information, the `csv` module provides numerous options for doing so. For example: In [1]: import csv In [2]: s = '1,2,3,"four, five",6' In [3]: for item in csv.reader([s]): ...: print item ...: ...: ['1', '2', '3', 'four, five', '6'] Here we use the `csv` module to read the string, and the `item` returned represents the comma-separated string, but with the special `"four, five"` value still treated as one value. However note that in the case of a single string, this returns a single list comprised of the comma-separated string elements. As @JonClements points out, a clean way to iterate through the elements themselves is to call `next` on `csv.reader([s])`, which will return the list itself: In [1]: import csv In [2]: s = '1,2,3,"four, five",6' In [3]: for item in next(csv.reader([s])): ...: print item ...: ...: 1 2 3 four, five 6
How to use a cython definition file (pxd) without making it an extension ? Question: What is the simplest way to create a pxd definition file, which simply collects cdefs replicated over pyx files, without creating new extensions? My case is the following: I would like to gather some extern cdefs in a pxd file (hp/src/common.pxd). I've also added some non-extern cdef, whose implementation is in common.pyx. In another pyx file (hp/src/_lib.pyx), which I turn into an extension, I cimport some stuff from common. In the setup.py file I create the following extension: Extension('hp._lib', ['hp/src/_lib.pyx'], language='c++'), By doing so, no common.cpp file is created, so it looks like dependencies are not automatically handled. That's the first problem. Then, manually running 'cython --cplus common.pyx' correctly creates a common.cpp file in the directory hp/src, and if I add 'hp/src/common.cpp' to the list of the extension sources, the command python setup.py installs everything without complaint, but then, importing the module hp triggers an ImportError: No module named common... from _lib.cpp... I'm stuck here. Any idea? Answer: You can include material from another file using the `include` statement. See the documentation here: <http://docs.cython.org/src/userguide/language_basics.html#the-include- statement> If you have external definitions in `common.pxd` and implementations in `commond.pyx` you will need to include them both. For example, in `_lib.pyx`: include "common.pxd" include "common.pyx" The contents of these files will then be compiled into your `_lib` module as if they were textually included at that point. i.e. a `common.c` file will not be generated, but rather included with `_lib.c`. The Cython compiler doesn't recognise changes to includes when deciding if the `.c` file for the module needs to be regenerated, so remember to delete this before you recompile.
Read a File 8 Lines at a Time Python Question: Hello I am trying to read a file in Python 8 lines at a time and use the current 8 lines as str variables However I am unable to do this correctly and would appreciate any help with open("test.txt", 'r') as infile: lines_gen = islice(infile, 8) for lines in lines_gen: firstname = str(lines[0]) lastname = str(lines[1]) email = str(lines[2]) ... How can I achieve this *cheers And ty for any help Answer: Using the usual n things at a time pattern from itertools import izip with open("test.txt") as f: line_gen = izip(*[f]*8) for lines in line_gen: print lines firstname, lastname, email, fourth, fifth, sixth, seventh, eighth = lines ...
Progress of Python requests post Question: I am uploading a large file using the Python requests package, and I can't find any way to give data back about the progress of the upload. I have seen a number of progress meters for downloading a file, but these will not work for a file upload. The ideal solution would be some sort of callback method such as: def progress(percent): print percent r = requests.post(URL, files={'f':hugeFileHandle}, callback=progress) Thanks in advance for your help :) Answer: `requests` [doesn't support](https://github.com/kennethreitz/requests/issues/295) [upload](https://github.com/kennethreitz/requests/issues/952) [streaming](https://github.com/shazow/urllib3/issues/51) e.g.: import os import sys import requests # pip install requests class upload_in_chunks(object): def __init__(self, filename, chunksize=1 << 13): self.filename = filename self.chunksize = chunksize self.totalsize = os.path.getsize(filename) self.readsofar = 0 def __iter__(self): with open(self.filename, 'rb') as file: while True: data = file.read(self.chunksize) if not data: sys.stderr.write("\n") break self.readsofar += len(data) percent = self.readsofar * 1e2 / self.totalsize sys.stderr.write("\r{percent:3.0f}%".format(percent=percent)) yield data def __len__(self): return self.totalsize # XXX fails r = requests.post("http://httpbin.org/post", data=upload_in_chunks(__file__, chunksize=10)) btw, if you don't need to report progress; [you could use memory-mapped file to upload large file](http://stackoverflow.com/questions/2502596/python-http- post-a-large-file-with-streaming). To workaround it, you could create a file adaptor similar to the one from [urllib2 POST progress monitoring](http://stackoverflow.com/questions/5925028/urllib2-post-progress- monitoring): class IterableToFileAdapter(object): def __init__(self, iterable): self.iterator = iter(iterable) self.length = len(iterable) def read(self, size=-1): # TBD: add buffer for `len(data) > size` case return next(self.iterator, b'') def __len__(self): return self.length ### Example it = upload_in_chunks(__file__, 10) r = requests.post("http://httpbin.org/post", data=IterableToFileAdapter(it)) # pretty print import json json.dump(r.json, sys.stdout, indent=4, ensure_ascii=False)
data stored by pylibmc cannot be uncompressed in php memcached Question: We have an application where we are using python to store lots of data in memcached.We are using pylibmc in python and on php side we are using php- memcached library.As a summary * pylibmc v.1.2.3 * php-memcached v.2.0.1 * libmemcached v1.0.8. Everything else is fine except when compression comes into play. This is how data is compressed in python import pylibmc mem = pylibmc.Client(['10.90.15.104:11211'], binary=True) mem.set('foo','this is a rather long string. this is a rather '+ 'long string. this is a rather long string. this is a rather' + 'long string. this is a rather long string', 0, 10) checking in telnet we see some garbled value, which means it was compressed. Now reading it in php. $memd = new Memcached(); $memd->addServer('10.90.15.104', 11211); echo $memd->get('foo'); When above is run, we get same garbled value, which means it is not getting uncompressed. pylibmc is using zlib, so accordingly I have changed php's compression type to zlib also. What other setting needs to be done? Please help. For further reference here are the memcached's output after setting the string in python pylibmc get foo VALUE foo 8 40 x+��,V�D��Ē��"����t�⒢̼t=���g\5# END And here's memcached's output for string stored using PHP's memcached client: get foo VALUE foo 48 44 �x�+��,V�D��Ē��"����t�⒢̼t=���g\5# END As you can see there's something fishy in this. Compressed size in pylibmc is 40 bytes and the same data compressed using php-memcached is of 44 bytes. Also notice the flags as 8 when stored using pylibmc and 48 when stored using php- memcached ! Answer: i think what you observe is due to the fact that memcache itself does not implement compression so each library does it in their own way, just compare the flags used to indicate compression is in use as defined by [pylibmc](https://github.com/lericson/pylibmc/blob/master/src/_pylibmcmodule.h#L63) `#define PYLIBMC_FLAG_ZLIB (1 << 3)` (so this is flag == 8) and by [php-memcached](https://github.com/php-memcached-dev/php- memcached/blob/master/php_memcached.c#L120) `#define MEMC_VAL_COMPRESSED (1<<4)` `#define MEMC_VAL_COMPRESSION_ZLIB (1<<5)` `#define MEMC_VAL_COMPRESSION_FASTLZ (1<<6)` so i think unless you are willing to modify one of this libraries to make it's flags consistent with the other then there is no way out **Edit:** Ok, so here is the little patch that bring compression support for pylibmc and php-memcached in sync. See my github [fork of pylibmc](https://github.com/gluedig/pylibmc). **Big fat warring** \- it works only on strings, so if you want to store objects you MUST do de/serialization on your own (JSON).
Writing Calculated Info to the front of a text file in Python Question: So I found this crappy old laptop (my now moved out sister's from about '05) in my basement and I've been messing around with it by running huge calculations on it in Python and leaving it for hours. My newest project is saving the first 1 billion primes to a text file (pointless, I know, but somewhat interesting) So heres my code so far: from time import time start_time = time() f = open('primes.txt', 'w') counter = 1 number = 1 while counter <= 1000000000: if prime(number): #NOTE: prime is a function checking if a number is prime f.write(str(counter) + ' ' + str(number) + '\n') counter += 1 number += 1 f.write(time() - start_time) f.write('This file contains the first %s primes.' % (counter)) f.close The issue I have is at the end. I want the time and prime to be listed on the first line of the file, not the end, because a billion primes is a very long text file. Obviously I can't write it before the primes are calculated / written, because the time and prime will both be 0. Is there any way to, after the calculation and writing is done, to insert the info to the start (first line) of the file? SOLVED! Adding whitespace at the start and then using f.seek(0) worked perfectly. As for the program, the first 100 million took around 3 days! Clearly not the most efficient program, but it is also only running on 1 core which is only 800 MHz Answer: you can write some whitespace at the beginning of the file f.write(" "*30) and then, when you finished calculating, you go back to the beginning and overwrite this white space: f.seek(0) f.write(str(counter)+" primes")
Ip list from captured pcap python Question: I'm trying to sort a previously-captured Pcap file, I want to build a list of ip source and destinations, so I can run calculation against them. I have attempted to search the pcap file using a search function but this fails with ip addresses, any ideas? Eventually I want the code to sniff live using the folowing code then build a list if the ip addresses. newpkt = sniff(count = 100, prn=lambda x:x.sprintf("{IP:%IP.src% -> %IP.dst%\n} {Raw:%Raw.load%\n}")) Answer: here is the result for anyone who might need it from scapy.all import * pkts = rdpcap("capture.cap") test = "" for pkt in pkts: temp = pkt.sprintf("%IP.src%,%IP.dst%,") test = test + temp print test
Obtaining MD5 hash value from online image / movie using Python Question: I'm currently looking to put together a quick script using Python 2.x to try and obtain the MD5 hash value of a number of images and movies on specific websites. I have noted on the w3.org website that the HTTP/1.1 protocol does offer an option within the content field to access the MD5 value but I'm wondering if this has to be set by the website admin? My script is as below:- import httplib c = httplib.HTTPConnection("www.samplesite.com") c.request("HEAD", "/sampleimage.jpg") r = c.getresponse() res = r.getheaders() print res I have a feeling I need to edit 'HEAD' or possibly r.getheaders but I'm just not sure what to replace them with. Any suggestions? As said, I'm just looking to point at an image and to then capture the MD5 hash value of the said image / movie. Ideally I don't want to have to download the image / movie to save bandwidth hence why I'm trying to do it this way. Thanks in advance Answer: Yes, it's rare that servers will actually respond to requests with an MD5 header. You _can_ check for that, but in most cases, you'll actually need to download the video or image, unfortunately. (At least [`hashlib`](http://docs.python.org/2/library/hashlib.html#module- hashlib) is simple!)
Python urllib2: Receive JSON response from url Question: I am trying to GET a URL using Python and the response is JSON. However, when I run import urllib2 response = urllib2.urlopen('https://api.instagram.com/v1/tags/pizza/media/XXXXXX') html=response.read() print html The html is of type str and I am expecting a JSON. Is there any way I can capture the response as JSON or a python dictionary instead of a str. Answer: If the URL is returning valid JSON-encoded data, use the [`json` library](http://docs.python.org/2/library/json.html) to decode that: import urllib2 import json response = urllib2.urlopen('https://api.instagram.com/v1/tags/pizza/media/XXXXXX') data = json.load(response) print data
Displaying Pretty Python Code in Python (or Other) GUI Question: I'm starting a simple little GUI for grading my student's python source code. Is there an easy way to automatically format display of the python code within a GUI? For example, pulling the color formatting from some editor? I've started with Python tkk (just for a little extra python practice, I teach it but don't use it much) but I have no objections switching languages if it is easier in this aspect. The output will a webpage with all the grades etc, but will show the python code using Google Prettify (unless someone has a better suggestion), so I don't need to keep the color scheme, just want it displayed to make grading easier. Many thanks! Answer: As @icktoofay said, you can use Pygments. PyQt/PiSide, PyGtk and wxPython all have WebKit widgets. Here's an example using PyGTK (note - not an expert in PyGtk): #!/usr/bin/env python '''Example on using Pygments and gtk/webkit''' from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import HtmlFormatter import gtk import webkit def gen_html(path): '''Generate HTML for Python file with embedded CSS.''' with open(path) as fo: code = fo.read() formatter = HtmlFormatter(linenos='table') css = formatter.get_style_defs() div = highlight(code, PythonLexer(), formatter) return '''<html> <head><style>{}</style></head> <body><div>{}</div></body> </html>'''.format(css, div) def get_file(): '''Get file from user.''' dlg = gtk.FileChooserDialog( title=None,action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK)) dlg.set_default_response(gtk.RESPONSE_OK) # Only Python files filter = gtk.FileFilter() filter.set_name("Python files") filter.add_pattern("*.py") dlg.add_filter(filter) path = dlg.get_filename() if dlg.run() == gtk.RESPONSE_OK else None dlg.destroy() return path def load(view): '''Load a new file''' path = get_file() if not path: return html = gen_html(path) with open('/tmp/src.html', 'w') as fo: fo.write(html) view.load_html_string(html, '/') if __name__ == '__main__': box = gtk.VBox() # WebKit view in scroll view = webkit.WebView() sw = gtk.ScrolledWindow() sw.add(view) sw.set_size_request(600, 400) box.pack_start(sw) # Open file btn = gtk.Button('Open...') btn.connect('clicked', lambda e: load(view)) box.pack_start(btn, False, False, 0) # Quit btn = gtk.Button('Quit') btn.connect('clicked', lambda e: gtk.main_quit()) box.pack_start(btn, False, False, 0) # Main window win = gtk.Window(gtk.WINDOW_TOPLEVEL) win.add(box) win.show_all() gtk.main()
How to implement Semaphores in python 2.x when not using default RUN method Question: The code flow is something as below. result = [] def Discover(myList=[]): for item in myList: t = threading.Thread(target=myFunc, Args=[item]) t.start() def myFunc(item): result.append(item+item) Now this will start multiple threads and in current scenario the threads does some memory intensive Tasks. Thus I want to include semaphores in this so that myList behaves as a queue and number of threads must be in a limited size. What is the better way to do that? Answer: 1. Never use mutable objects as default parameter value in function definition. In your case: `def Discover(myList=[])` 2. Use `Queue.Queue` instead of `list` to provide `myList` if it's necessary to update list of "tasks" when threads are running. Or... Use `multiprocessing.pool.ThreadPool` in order to limit number of running threads at the same time. 3. Use `Queue.Queue` instead of `list` to provide `results` variable. `list` implementation is not thread-safe, so you probably will get many problems with it. 4. You can find some examples in other SO questions, i.e. [here](http://stackoverflow.com/questions/2846653/python-multithreading-for-dummies). P.S. `ThreadPool` available in Python 2.7+ $ python Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from multiprocessing.pool import ThreadPool >>> ThreadPool <class 'multiprocessing.pool.ThreadPool'>
Inherit a parent class docstring as __doc__ attribute Question: There is a question about [Inherit docstrings in Python class inheritance](http://stackoverflow.com/questions/2025562/inherit-docstrings-in- python-class-inheritance), but the answers there deal with method docstrings. My question is how to inherit a docstring of a parent class as the `__doc__` attribute. The usecase is that [Django rest framework](http://django-rest- framework.org) generates nice documentation in the html version of your API based on your view classes' docstrings. But when inheriting a base class (with a docstring) in a class without a docstring, the API doesn't show the docstring. It might very well be that sphinx and other tools do the right thing and handle the docstring inheritance for me, but django rest framework looks at the (empty) `.__doc__` attribute. class ParentWithDocstring(object): """Parent docstring""" pass class SubClassWithoutDoctring(ParentWithDocstring): pass parent = ParentWithDocstring() print parent.__doc__ # Prints "Parent docstring". subclass = SubClassWithoutDoctring() print subclass.__doc__ # Prints "None" I've tried something like `super(SubClassWithoutDocstring, self).__doc__`, but that also only got me a `None`. Answer: Since you cannot assign a new `__doc__` docstring to a class (in CPython at least), you'll have to use a metaclass: import inspect def inheritdocstring(name, bases, attrs): if not '__doc__' in attrs: # create a temporary 'parent' to (greatly) simplify the MRO search temp = type('temporaryclass', bases, {}) for cls in inspect.getmro(temp): if cls.__doc__ is not None: attrs['__doc__'] = cls.__doc__ break return type(name, bases, attrs) Yes, we jump through an extra hoop or two, but the above metaclass will find the correct `__doc__` however convoluted you make your inheritance graph. Usage: >>> class ParentWithDocstring(object): ... """Parent docstring""" ... >>> class SubClassWithoutDocstring(ParentWithDocstring): ... __metaclass__ = inheritdocstring ... >>> SubClassWithoutDocstring.__doc__ 'Parent docstring' The alternative is to set `__doc__` in `__init__`, as an instance variable: def __init__(self): try: self.__doc__ = next(cls.__doc__ for cls in inspect.getmro(type(self)) if cls.__doc__ is not None) except StopIteration: pass Then at least your instances have a docstring: >>> class SubClassWithoutDocstring(ParentWithDocstring): ... def __init__(self): ... try: ... self.__doc__ = next(cls.__doc__ for cls in inspect.getmro(type(self)) if cls.__doc__ is not None) ... except StopIteration: ... pass ... >>> SubClassWithoutDocstring().__doc__ 'Parent docstring' As of Python 3.3 (which fixed [issue 12773](http://bugs.python.org/issue12773)), you _can_ finally just set the `__doc__` attribute of custom classes, so then you can use a class decorator instead: import inspect def inheritdocstring(cls): for base in inspect.getmro(cls): if base.__doc__ is not None: cls.__doc__ = base.__doc__ break return cls which then can be applied thus: >>> @inheritdocstring ... class SubClassWithoutDocstring(ParentWithDocstring): ... pass ... >>> SubClassWithoutDocstring.__doc__ 'Parent docstring'
Cannot iterate VBA macros from Python Question: I am using VBA in conjunction with Python. I imported the module OS, and for working with excel - openpyxl. The problem occurs when it iterates the function for running the VBA macro from Excel. import random from openpyxl import load_workbook import os, os.path, win32com.client wbi = load_workbook('Input.xlsm') wsi = wbi.get_active_sheet() wbo = load_workbook('Output.xlsx') wso = wbo.get_active_sheet() def run_macro(fName, macName, path=os.getcwd()): """ pre: fName is the name of a valid Excel file with macro macName post: fName!macName is run, fName saved and closed """ fName = os.path.join(path, fName) xlApp = win32com.client.Dispatch("Excel.Application") fTest = xlApp.Workbooks.Open(fName) macName = fTest.Name + '!' + macName xlApp.Run(macName) fTest.Close(1) xlApp.Quit() xlApp = None def IBP(): ibp = wsi.cell('G12') ibpv = random.randint(0,45) ibp.value = ibpv return ibp.value def BP10(): bp10 = wsi.cell('G13') bpv10 = random.randint(30,50) bp10.value = bpv10 return bp10.value for n in range(6): IBP() print IBP() BP10() run_macro('Input.xlsm','macro1') wbo.save('Output.xlsx') I think that the error is in `run_macro('Input.xlsm','macro1')` \- it cannot iterate. **The output:** Qt: Untested Windows version 6.2 detected! 35 4 Traceback (most recent call last): File "C:\Users\User\Desktop\Python Exp\Pr 1.py", line 77, in <module> run_macro('Input.xlsm','macro1') File "C:\Users\User\Desktop\Python Exp\Pr 1.py", line 18, in run_macro fTest = xlApp.Workbooks.Open(fName) File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 522, in __getattr__ raise AttributeError("%s.%s" % (self._username_, attr)) AttributeError: Excel.Application.Workbooks What am I doing wrong? Answer: I'm not sure this will help, but you can try early binding. Run this script and then try yours again: import win32com.client xl = win32com.client.gencache.EnsureDispatch ("Excel.Application") print xl.__module__ If that does not work, you can alway go back to late binding by hooking to Excel like this: xl = win32com.client.dynamic.Dispatch("Excel.Application") or by simply deleting this folder: `C:\Python27\Lib\site- packages\win32com\gen_py\00020813-0000-0000-C000-000000000046x0x1x7` From the error message, it looks like your problem is on the line `wb = xlApp.Workbooks.Open(fname)`. If the Python hooks to the Excel com servers were working correctly, then that line would not raise the exception that it did. I don't see anything wrong with the code where the exception occured. Sometimes early binding helps in situations like this. good luck Mike
Job scheduling with `at`. "EOF: not found" Question: I am trying to schedule a job on a remote server. I want this job to be scheduled either a minute from the current server time or a minute from the server time of the last scheduled job to run on the server. This way, no two jobs run at the same time (and thus race conditions are avoided). The job scheduling is done with the `at` command on the remote (linux) server. I am forced to use `at` because I am running a bunch of complex simulations on several hosts that connect to the same server to request the next simulation (this part has been omitted from my question for brevity). I am running into problems trying to schedule the job to run at a minute after the last scheduled job (or a minute from now if there are no scheduled jobs). My scheduler script currently looks like this: minute=`atq | sort -t" " -k1 -nr | head -n1 | cut -d' ' -f4 | cut -d":" -f1,2` curr=`date | cut -d' ' -f4 | cut -d':' -f1,2` # the 'python -c" prints the correct scheduling time to stdout cat <<EOF | at `python -c "import sys; hour,minute=map(int,max(sys.argv[1:]).split(':')); minute += 1; hour, minute = [(hour,minute), ((hour+1)%24,(minute+2)%60)][minute>=60]; print '%d:%02d'%(hour, minute)" "$minute" "$curr"` python path/to/somescript "$1" EOF However, with this script, I get the following error: somescript: 8: EOF: not found However, if I were to hardcode the time as follows, that error disappears and the scheduling proceeds as expected: minute=`atq | sort -t" " -k1 -nr | head -n1 | cut -d' ' -f4 | cut -d":" -f1,2` curr=`date | cut -d' ' -f4 | cut -d':' -f1,2` cat <<EOF | at 16:48 # or whatever other time python path/to/somescript "$1" EOF I'd appreciate any help on how to fix this error as my entire setup goes bonkers as a result of this error. Thank you Answer: just a thought. instead of using the here doc why not create a temporary file and get rid of the EOF issue ? or do this : echo python path/to/somescript "$1" | at `python -c "import sys; hour,minute=map(int,max(sys.argv[1:]).split(':')); minute += 1; hour, minute = [(hour,minute), ((hour+1)%24,(minute+2)%60)][minute>=60]; print '%d:%02d'%(hour, minute)" "$minute" "$curr"` would get rid of the EOF, and maybe you could see the error better. I'm guessing the python code barfs on some weird condition, missing lead zero, am/pm, something that I just don't see at the moment.
Manipulate string data Question: I'm new to python and trying to create a script to modify the output of a JS file to match what is required to send data to an API. The JS file is being read via urllib2. def getPage(): url = "http://url:port/min_day.js" req = urllib2.Request(url) response = urllib2.urlopen(req) return response.read() # JS Data # m[mi++]="19.12.12 09:30:00|1964;2121;3440;293;60" # m[mi++]="19.12.12 09:25:00|1911;2060;3277;293;59" # Required format for API # addbatchstatus.jsp?data=20121219,09:25,3277.0,1911,-1,-1,59.0,293.0;20121219,09:30,3440.0,1964,-1,-1,60.0,293.0 As a breakdown (Required values are bold) m[mi++]="**19.12.12** **09:30:00** |**1964** ;2121;**3440** ;**293** ;**60** " and need to add values of -1,-1 into the string I've managed to get the date into the correct format and replace characters and line breaks to make the output look as such, but I have a feeling I'm heading down the wrong track if I need to be able to reorder this string values. Although it looks like the order is in reverse in regards to time as well. 20121219,09:30:00,1964,2121,3440,293,60;20121219,09:25:00,1911,2060,3277,293,59 Any help would be greatly appreciated! I'm thinking along the lines of regex might be what I need. Answer: Here's a Regex pattern to strip out the bits you don't want > `m\[mi\+\+\]="(?P<day>\d{2})\.(?P<month>\d{2})\.(?P<year>\d{2}) > (?P<time>[\d:]{8})\|(?P<v1>\d+);(?P<v2>\d+);(?P<v3>\d+);(?P<v4>\d+);(?P<v5>\d+).+` and replace with > `20\P<year>\P<month>\P<day>,\P<time>,\P<v3>,\P<v1>,-1,-1,\P<v5>,\P<v4>` This pattern assumes that the characters before the date are constant. You can replace `m\[mi\+\+\]="` with `[^\d]+` if you want more general handling of that bit. So to put this in practice in python: import re def getPage(): url = "http://url:port/min_day.js" req = urllib2.Request(url) response = urllib2.urlopen(req) return response.read() def repl(match): return '20%s%s%s,%s,%s,%s,-1,-1,%s,%s'%(match.group('year'), match.group('month'), match.group('day'), match.group('time'), match.group('v3'), match.group('v1'), match.group('v5'), match.group('v4')) pattern = re.compile(r'm\[mi\+\+\]="(?P<day>\d{2})\.(?P<month>\d{2})\.(?P<year>\d{2}) (?P<time>[\d:]{8})\|(?P<v1>\d+);(?P<v2>\d+);(?P<v3>\d+);(?P<v4>\d+);(?P<v5>\d+).+') data = [re.sub(pattern, repl, line).split(',') for line in getPage().split('\n')] # If you want to sort your data data = sorted(data, key=lambda x:x[0], reverse=True) # If you want to write your data back to a formatted string new_string = ';'.join(','.join(x) for x in data) # If you want to write it back to file with open('new/file.txt', 'w') as f: f.write(new_string) Hope that helps!
PyInstaller 2.0 bundle file as --onefile Question: I'm trying to bundle my py script as an .exe using PyInstaller 2.0. I am able to bundle the script, but in my script, I need to open a file that should be bundled in the exe (so it's portable). I'm having trouble doing this.. In my .py, I have filename = 'C:\path\to\my\file\doc.docx' data = open(filename,'rb') I use PyInstaller 2.0 and this works fine on my computer, but if I transfer the exe to another computer it isn't going to work.. PyInstaller 2.0 is pretty new, so there are very few documents on it, and the publisher's documentation is quite "lacking." Here is the publisher's info on the matter: (I don't think their documentation is up to date, because in the beginning it says use Configure.py, then in other docs it says Configure.py is no longer needed in 2.0) > In a --onefile distribution, data files are bundled within the executable > and then extracted at runtime into the work directory by the C code (which > is also able to reconstruct directory trees). The work directory is best > found by os.environ['_MEIPASS2']. So, you can access those files through: os.path.join(os.environ["_MEIPASS2"], relativename)) That doesn't really make sense to me, a beginning programmer.. A different document from the publisher says.. > In a --onefile distribution, data files are bundled within the executable > and then extracted at runtime into the work directory by the C code (which > is also able to reconstruct directory trees). The work directory is best > found by sys._MEIPASS. So, you can access those files through: os.path.join(sys._MEIPASS, relativename)) I've experimented around quite a bit with os.environ["_MEIPASS2"] and python doesn't seem to understand os.environment["_MEIPASS2"]. I get this back: >>> print os.environ["_MEIPASS2"] Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> print os.environ["_MEIPASS2"] File "C:\Python27\lib\os.py", line 423, in __getitem__ return self.data[key.upper()] KeyError: '_MEIPASS2' I also experimented with sys._MEIPASS.. Yeah, python responds 'module' has no attribute '_MEIPASS'. At this point, I feel like my head is about to explode.. I appreciate PyInstaller's authors for their work, but their documentation is the worst I've ever seen! I just need someone to help me bundle my file into the exe. I would really like to use PyInstaller 2.0+ since all the .spec stuff confuses me with previous versions of PyInstaller. BTW, I'm using Win8 64bit with python 2.7.3 PLEASE HELP! Answer: OMG! This PyInstaller really confused me for a bit. If my previous post sounds a little "ranty", sorry about that.. Anyways, for anyone trying to include a file in a --onefile PyInstaller package this worked for me: Include this in your .py script: filename = 'myfilesname.type' if hasattr(sys, '_MEIPASS'): # PyInstaller >= 1.6 chdir(sys._MEIPASS) filename = join(sys._MEIPASS, filename) elif '_MEIPASS2' in environ: # PyInstaller < 1.6 (tested on 1.5 only) chdir(environ['_MEIPASS2']) filename = join(environ['_MEIPASS2'], filename) else: chdir(dirname(sys.argv[0])) filename = join(dirname(sys.argv[0]), filename) credit to someone online whose name I don't remember.. (sorry it's late and I'm exhausted!) Then, if you're using PyInstaller2.0, in cmd, from the pyinstaller-2.0 dir, you can run pyinstaller.py --onefile myscriptsname.py That will create a myscriptsname.spec file in the pyinstaller-2.0 dir. It will also create an exe, but that won't work. It will be updated later. Now edit that .spec, and add the following a.datas line (remember datas, not data). I included a little extra in the .spec file just for reference. a = Analysis(['ServerTimeTest_nograph.py'], pathex=['c:\\Python27\\pyinstaller-2.0'], hiddenimports=[], hookspath=None) a.datas += [('myfilesname.type','C:\\path\\to\\my\\file\\myfilesname.type','DATA')] pyz = PYZ(a.pure) Now, back in cmd, run pyinstaller.py --onefile myscriptsname.spec This will update your .exe in the /dist dir. Maybe there's a better way, or a prettier way, but this worked for me!
python create jpg file from raw data Question: I have this strange xml file which apparently contains jpeg image data: <?xml version="1.0" encoding="UTF-8"?> <AttachmentDocument xmlns="http://echa.europa.eu/schemas/iuclid5/20070330" documentReferencePK="ECB5-d18039fe-6fb0-44d6-be9e-d6ade38be543/0" encoding="0" fileSize="5788" fileTimestamp="2007-04-17T12:38:44Z" parentDocumentPK="ECB5-fb07efbf-ee93-4cdd-865b-49efa51cbd15/0" version="2007-03-19T14:13:29Z"> <modificationHistory> <modification date="2007-05-10T09:00:00Z"> <comment>Created</comment> <modificationBy>European Commision/Joint Research Centre/European Chemicals Bureau</modificationBy> </modification> </modificationHistory> <ownershipProtection copyProtection="false" fractionalDocument="false" sealed="false"/> <fileName>33952-38-4-V2.jpeg</fileName> <fileMimetype>image/jpeg</fileMimetype> <rawContent> H4sIAAAAAAAAAO2XZ1AU65qAe5iBIQwgOCMZRkHJCIgEySBhyEEyIyDgMBKHLEFQBJEoIHBEQFQE JUjOSo4iOQ+Ss2QkSZhZvLXn7j11726d3draH1vn7Xp+dH1fd/XzvV+//TZxlDgNnNNQRakCIBAA gM4OgEgA5JQNVBRv6RrcQGLsBO+52WOQ3iJCwkgeLw+sCwaJ0lBDauipqCG9xUV5BZB29ndtvJw8 kTgvGyes531K4jigDJCTkUHJSMmhUCgFBTklDE4No6KCMdGfp4WzMXOwszGzsiK5hLiRlwQ4WVl5 ... </rawContent> <MD5>0d80850b0c4085500f80e1430b90c70910d4110cc0d7</MD5> </AttachmentDocument> (The full version [here](http://pastebin.com/X204p1rw)) And I can't read image out of it. My attempt: from PIL import Image import StringIO import base64 # I've eleminated all newlines and tabs to produce data string data="H4sIAAAAAAAAAO2XZ1AU65qAe5..." im = Image.open(StringIO.StringIO(base64.b64decode(data))) But I'm getting an error: File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1980, in open raise IOError("cannot identify image file") Answer: If you'd check what you're getting in the output of base64 decode, then you would notice that it's a gzip file. Extract the compressed file and you'll get the desired JPEG. Comment stored in the image: CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), default quality
AttributeError: 'module' object has no attribute 'Datefield' Question: In the file models.py from django.db import models # Create your models here. class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField() class Books(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publishers = models.ForeignKey(Publisher) publication_date = models.Datefield() When I run the command $ python manage.py validate I get the error message AttributeError: 'module' object has no attribute 'Datefield' Please help. Answer: It should be [`models.DateField`](https://docs.djangoproject.com/en/dev/ref/models/fields/#datefield) with a capital `F`. So your `Books` model should look like this: class Books(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publishers = models.ForeignKey(Publisher) publication_date = models.DateField() # <--- Typo was here
Python - Scheduling with stop and resume running task feature Question: I was developing a scheduling application, in the schedule there's many lamp that turn on and off in specific time, say if I start the schedule at morning all lamps will turn on then stop at night, but there is some lamp that need to stop at random time and also turn on again. I've tried some python package like APScheduler but it doesn't have feature to stop and resume a specific task (or lamp in this occasion). This [question](http://stackoverflow.com/questions/6299349/how-to-stop-and- resume-long-time-running-python-script) using pickle to stop and resume, but I don't know how to implement it, is there any way to solve this? Thanks in advance, sorry for my bad grammer. **\--UPDATE--** Here is simple implementation, I'm not sure this code is right. from datetime import datetime from time import sleep class Scheduling: def __init__(self): self.lamp = {} def run(self, lamp_id, start, finish): """Called one-time only for each lamp""" self.lamp[lamp_id] = (start, finish) while True: if datetime.now().strftime('%H:%M:%S') == start: sleep(1) print 'SET LAMP %s ON' % lamp_id elif datetime.now().strftime('%H:%M:%S') == finish: sleep(1) print 'SET LAMP %s OFF' % lamp_id def stop(self, lamp_id): print 'SET lamp %s OFF' % lamp_id def resume(self, lamp_id): print 'SET lamp %s ON' % lamp_id finish = self.lamp[lamp_id][1] while True: if datetime.now().strftime('%H:%M:%S') == finish: print 'SET lamp %s OFF' % lamp_id if __name__ == '__main__': schedule = Scheduling() schedule.run(1, '00:00:00', '00:01:00') Answer: I think you may be looking at this problem wrong. Viewing "lamp on" as a task to be stopped and resumed is overcomplicated. Really, what you have is a series of scheduled stateless events; turn a lamp on, turn a lamp off (and maybe toggle lamp, that turns it on if off or off if on). If you try to model the system that way, it will probably prove easier to set up a scheduler around.
Open multiple webpages with different parametrs. PyQt4 Question: I have followed the answer by [X.Jacobs](http://stackoverflow.com/users/1006989/x-jacobs) on this [Question](http://stackoverflow.com/questions/13943558/multiple-threads-of- qwebview-in-pyqt4), and was trying to create an app that will open multiple windows with different parameters, but it doesn't work, looks, like app is opening windows, but not load the webpage. #! /usr/bin/env python2.7 from PyQt4.QtCore import * from PyQt4.QtGui import* from PyQt4.QtWebKit import * import sys, signal url = 'http://http://forums.fedoraforum.org/showthread.php?t={0}' class Opener(QWebView): def __init__(self, param=None): QWebView.__init__(self) self.param = param self.loadFinished.connect(self.print_title) def print_title(self): print self.title() class Foo(QObject): def __init__(self): QObject.__init__(self) self.count = 0 self.params = range(4) self.mapper = QSignalMapper(self) self.mapper.mapped.connect(self.mapper_mapped) for i in range(2): opener = Opener() opener.loadFinished.connect(self.mapper.map) self.mapper.setMapping(opener, i) opener.loadFinished.emit(True) QTimer.singleShot(1, lambda:opener.loadFinished.emit(True)) def mapper_mapped(self, gNumber): self.count += 1 if self.count < len(self.params): gParam = self.params[self.count] opener = self.mapper.mapping(gNumber) opener.load(QUrl(url.format(gParam))) opener.show() QTimer.singleShot(1, lambda:opener.loadFinished.emit(True)) if __name__ == "__main__": app = QApplication(sys.argv) main = Foo() if signal.signal(signal.SIGINT, signal.SIG_DFL): sys.exit(app.exec_()) app_exec_() Answer: There's a couple of things going on in that code :) checkout this working version and see how you can adapt it to yours: #!/usr/bin/env python from PyQt4.QtCore import * from PyQt4.QtGui import* from PyQt4.QtWebKit import * class Foo(QWidget): def __init__(self, parent=None): super(Foo, self).__init__(parent) self.count = 0 self.params = range(4) self.url = 'http://forums.fedoraforum.org/showthread.php?t={0}' self.gridLayout = QGridLayout(self) self.tabWidget = QTabWidget(self) self.gridLayout.addWidget(self.tabWidget, 0, 0, 1, 1) self.mapper = QSignalMapper(self) self.mapper.mapped.connect(self.on_mapper_mapped) for i in range(2): grabber = QWebView() grabber.loadFinished.connect(self.mapper.map) self.mapper.setMapping(grabber, i) self.tabWidget.addTab(grabber, "opener {0}".format(str(i))) grabber.loadFinished.emit(True) @pyqtSlot(int) def on_mapper_mapped(self, gNumber): self.count += 1 if self.count < len(self.params): gParam = self.params[self.count] opener = self.mapper.mapping(gNumber) opener.load(QUrl(self.url.format(gParam))) if __name__ == "__main__": import sys app = QApplication(sys.argv) main = Foo() main.show() app.exec_()
Can I use Python requests with celery? Question: I have the following defined in a celery module named tasks.py with the requests library imported: @celery.task def geturl(url): res = requests.get(url) return res.content Whenever I call the task (either from tasks.py or REPL) with: res = geturl.delay('http://www.google.com') print res.get() Here are the log entries on the celery server: [2012-12-19 18:49:58,400: INFO/MainProcess] Starting new HTTP connection (1): www.google.com [2012-12-19 18:49:58,594: INFO/MainProcess] Starting new HTTP connection (1): www.google.ca [2012-12-19 18:49:58,801: INFO/MainProcess] Task tasks.geturl[48182400-7d67-466b-ba5c-867747cb3974] succeeded in 0.402245998383s: None But when I run this in a synchronous fashion by calling geturl('http://www.google.com'), I get a response. I have read through the docs and cannot seem to clue into why this is not working. The primary use of this is to poll API's could someone please explain why this does not work? Thanks! Answer: `res.content` is just an `str` instance, there's no reason you wouldn't be able to return it. Your issue likely lies elsewhere, probably in your celery configuration. * * * [Many configuration parameters play a role in how the results will be stored](http://docs.celeryproject.org/en/latest/configuration.html#task- execution-settings); have a look at them. The first one you'll want to check may be `CELERY_IGNORE_RESULT`. Your should also check your result broker configuration.
Download a file using Python Question: I have to download a number of files. I tried the following code in python. import urllib2 ul = urllib2.urlopen('http://dds.cr.usgs.gov/emodis/Africa/historical/TERRA/2012/comp_056/AF_eMTH_NDVI.2012.047-056.QKM.COMPRES.005.2012059143841.zip.sum').read() open("D:/Thesis/test_http_dl", "w").write(ul) It throws this error: IOError: [Errno 13] Permission denied: 'D:/Thesis/test_http_dl' Do you have any idea why is that? Am I doing something wrong? I have tried different folders and it didn't work. My folders are not read only. the result of `print(repr(ul[:60]))` is `'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n<htm'`. `urllib.urlretrieve()` just creates a 1 kb file in the folder, which obviously is not the downloaded file. Answer: The error tells you exactly what went wrong. You don't have permission to write to path `D:/Thesis/test_http_dl`. There are four possible reasons for that: 1. You already have a file with that name, which you don't have write access to. 2. You don't have access to create new files in `D:\Thesis`. 3. You don't have write access to the D: drive at all (e.g., because it's a CD-ROM). 4. Some other process has the file open for exclusive access. You need to look at the ACLs for `D:\Thesis\test_http_dl` if it exists, or for `D:\Thesis\` otherwise, and see if your user (the one you're running the script as) has write access, and also check whether that path or the D drive itself has the "read-only" flag on, and also check whether any other process has the file open. (I don't know of any built-in tool for that last one, but `handle` or `Process Explorer` from [sysinternals](http://technet.microsoft.com/en-US/sysinternals) can do it for you easily.) Meanwhile, none of the stuff with `urllib2` is at all relevant here. You can verify that by just doing this: open("D:/Thesis/test_http_dl", "w") You will get the exact same exception. It's worth knowing how to figure that out the "hard" way, for cases where the exception _doesn't_ tell you exactly what's wrong. You get an exception in a line like this: open("D:/Thesis/test_http_dl", "w").write(ul) Something is wrong, and if you don't have enough information to tell what it is, what do you do? Well, first, break it into pieces, so each line has exactly one operation: f = open("D:/Thesis/test_http_dl", "w") f.write(ul) Now you know which one of those two gets an exception. While you're at it, since the only thing this code depends on is `ul`, you can create a simpler program to test this: ul = 'junk' f = open("D:/Thesis/test_http_dl", "w") f.write(ul) Even if that doesn't help you directly, it means you don't need to wait for the download every time through the test loop, and you've got something simpler to post to SO (see [SSCCE](http://sscce.org) for more), and this is something you can just type into the interactive interpreter. Instead of trying to guess what might be useful to print out to see why the `write` is raising an exception, you can start with `help(f)` or `dir(f)` and play with it live. (In this case, I'm guessing it's actually the `open` that fails, not the `write`, but you shouldn't have to guess.) On to your second problem: > urllib.urlretrieve() just creates a 1 kb file in the folder, which obviously > is not the downloaded file. Actually, I think it _is_ the downloaded file. You're not asking for `AF_eMTH_NDVI.2012.047-056.QKM.COMPRES.005.2012059143841.zip`, you're asking for `AF_eMTH_NDVI.2012.047-056.QKM.COMPRES.005.2012059143841.zip.sum`, which is probably a checksum file—a quasi-standard type of file that contains metadata that helps you make sure the file you're downloading wasn't damaged in transit or tampered with by a hacker. A typical checksum file has one or more lines, each mapping a downloadable file to a checksum or cryptographic hash digest, in some format, for a downloadable file. Sometimes they have three columns—the type of checksum/hash, the value of the checksum/hash in some stringified format, and the filename or full URL of the file. Sometimes the first column is omitted, and you have to know from elsewhere what type of checksum/hash is being used (often MD5 as a hex string). Sometimes the columns are in different orders. Sometimes they're separated by commas or tabs, or in fixed-width fields, or some other variation. At any rate, you'd expect a .sum file to be around 80 bytes long. If you look at it in Explorer or the `dir` command, it'll usually be rounded up to the nearest 1K. So, you should see a 1K file if you download this successfully. Meanwhile: > print(repr(ul[:60])) is '\n You should try printing out the rest of this, because it's probably some kind of document explaining, in human terms, what you're doing wrong. This could be because you need to pass a URL agent, a preferred encoding, a referer, or some other header. However, I tested the exact same line of code you used repeatedly, and `ul` is always: 1ba6437044bfa9259fa2d3da8f95aebd AF_eMTH_NDVI.2012.047-056.QKM.COMPRES.005.2012059143841.zip In other words, it's a perfectly valid checksum file, not an HTML page. So, I suspect what's really going on is that you aren't testing the same code you're showing us.
Converting Matlab's datenum format to Python Question: I just started moving from Matlab to Python 2.7 and I have some trouble reading my .mat-files. Time information is stored in Matlab's datenum format. For those who are not familiar with it: > A serial date number represents a calendar date as the number of days that > has passed since a fixed base date. In MATLAB, serial date number 1 is > January 1, 0000. > > MATLAB also uses serial time to represent fractions of days beginning at > midnight; for example, 6 p.m. equals 0.75 serial days. So the string > '31-Oct-2003, 6:00 PM' in MATLAB is date number 731885.75. > > (taken from the Matlab documentation) I would like to convert this to Pythons time format and I found [this tutorial](http://sociograph.blogspot.de/2011/04/how-to-avoid-gotcha-when- converting.html). In short, the author states that > If you parse this using python's `datetime.fromordinal(731965.04835648148)` > then the result might look reasonable [...] (before any further conversions), which doesn't work for me, since datetime.fromordinal expects an integer: >>> datetime.fromordinal(731965.04835648148) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: integer argument expected, got float While I could just round them down for daily data, I actually need to import minutely time series. Does anyone have a solution for this problem? I would like to avoid reformatting my .mat files since there's a lot of them and my colleagues need to work with them as well. If it helps, [someone else asked for the other way round](http://stackoverflow.com/questions/8776414/python-datetime-to-matlab- datenum). Sadly, I'm too new to Python to really understand what is happening there. /edit (2012-11-01): This has been fixed in the tutorial posted above. Answer: You link to the solution, it has a small issue. It is this: python_datetime = datetime.fromordinal(int(matlab_datenum)) + timedelta(days=matlab_datenum%1) - timedelta(days = 366) a longer explanation can be found [here](http://sociograph.blogspot.com/2011/04/how-to-avoid-gotcha-when- converting.html)
How can I get the name of the script calling the function in python? Question: I know that `__file__` contains the filename containing the code, but is there a way to get the name of the script/file that's calling the function? If I have a file named `filenametest_b.py`: def printFilename(): print(__file__) And I import the function in `filenametest_a.py`: from filenametest_b import * printFilename() I get: C:\Users\a150495>python filenametest_a.py C:\Users\a150495\filenametest_b.py Is there something I can do in the `b` file to print the name of the `a` file? Answer: You could print `sys.argv[0]` to get the script filename. To get the filename of the caller, you need to use the [`sys._getframe()` function](http://docs.python.org/2/library/sys.html#sys._getframe) to get the calling frame, then you can retrieve the filename from that: import inspect, sys print inspect.getsourcefile(sys, sys._getframe(1))
What is a Pythonic way to count dictionary values in list of dictionaries Question: For a list like this: for i in range(100): things.append({'count':1}) for i in range(100): things.append({'count':2}) To count the number of `1` in list: len([i['count'] for i in things if i['count'] == 1]) What is a better way? Answer: [collections.Counter](http://docs.python.org/2/library/collections.html#collections.Counter) >>> from collections import Counter >>> c = Counter([thing['count'] for thing in things]) >>> c[1] # Number of elements with count==1 100 >>> c[2] # Number of elements with count==2 100 >>> c.most_common() # Most common elements [(1, 100), (2, 100)] >>> sum(c.values()) # Number of elements 200 >>> list(c) # List of unique counts [1, 2] >>> dict(c) # Converted to a dict {1: 100, 2: 100} * * * Perhaps you could do something like this? class DictCounter(object): def __init__(self, list_of_ds): for k,v in list_of_ds[0].items(): self.__dict__[k] = collections.Counter([d[k] for d in list_of_ds]) >>> new_things = [{'test': 1, 'count': 1} for i in range(10)] >>> for i in new_things[0:5]: i['count']=2 >>> d = DictCounter(new_things) >>> d.count Counter({1: 5, 2: 5}) >>> d.test Counter({1: 10}) Extended DictCounter to handle missing keys: >>> class DictCounter(object): def __init__(self, list_of_ds): keys = set(itertools.chain(*(i.keys() for i in list_of_ds))) for k in keys: self.__dict__[k] = collections.Counter([d.get(k) for d in list_of_ds]) >>> a = [{'test': 5, 'count': 4}, {'test': 3, 'other': 5}, {'test':3}, {'test':5}] >>> d = DictCounter(a) >>> d.test Counter({3: 2, 5: 2}) >>> d.count Counter({None: 3, 4: 1}) >>> d.other Counter({None: 3, 5: 1})
NZEC in python on spoj for AP2 Question: I wrote the following two codes ## FCTRL2.py import sys; def fact(x): res = 1 for i in range (1,x+1): res=res*i return res; t = int(raw_input()); for i in range (0,t): print fact(int(raw_input())); and ## AP2.py import sys; t = int(raw_input()); for i in range (0,t): x,y,z = map(int,sys.stdin.readline().split()) n = (2*z)/(x+y) d = (y-x)/(n-5) a = x-(2*d) print n for j in range(0,n): sys.stdout.write(a+j*d) sys.stdout.write(' ') print' ' FCTRL2.py is accepted on spoj whereas AP2.py gives NZEC error. Both work fine on my machine and i do not find much difference with regard to returning values from both. Please explain what is the difference in both and how do i avoid NZEC error for AP2.py Answer: There may be extra white spaces in the input. A good problem setter would ensure that the input satisfies the specified format. But since spoj allows almost anyone to add problems, issues like this sometimes arise. One way to mitigate white space issues is to read the input at once, and then tokenize it. import sys; # Why use ';'? It's so non-pythonic. inp = sys.stdin.read().split() # Take whitespaces as delimiter t = int(inp[0]) readAt = 1 for i in range (0,t): x,y,z = map(int,inp[readAt:readAt+3]) # Read the next three elements n = (2*z)/(x+y) d = (y-x)/(n-5) a = x-(2*d) print n #for j in range(0,n): # sys.stdout.write(a+j*d) # sys.stdout.write(' ') #print ' ' print ' '.join([str(a+ti*d) for ti in xrange(n)]) # More compact and faster readAt += 3 # Increment the index from which to start the next read
How to converter std::string* in boost.python? Question: How to converter std::string* in boost.python?I have to handle some data of c++ in python.The data may be big.So I return a pointer to python. But there are some errors. # c++ #include <boost/python.hpp> #include <string> class A { public: A() { data="342342fgsf"; ss=&data; } std::string *ss; std::string data; }; BOOST_PYTHON_MODULE(ctopy) { using namespace boost::python; class_<A> ("A",init<>()) .add_property(ss,&A::ss) ; } # python import ctopy t1=ctopy.A() print t1.ss #error.TypeError:No to_python (by-value) converter found for c++ type:std::string* Answer: You can't just pass pointer. Use `pointer_wrapper`: <http://www.boost.org/doc/libs/1_53_0/libs/python/doc/v2/ptr.html>
Python unicode string operation in App Engine failing Question: Python code that runs in Development/local machine, but fails after installing to Appengine : 1st line in my File : # -*- coding: utf8 -*-O Lines later in the code : s1 = u'Ismerőseid' logging.info (s1) s2 = s1 + u':' + s1 logging.info (s2) logging.info ("%s,%s", s1, s2) In Dev (localhost): INFO 2012-12-18 04:01:17,926 AppRun.py:662] Ismerőseid, INFO 2012-12-18 04:01:17,926 AppRun.py:664] Ismerőseid:Ismerőseid INFO 2012-12-18 04:01:17,926 AppRun.py:665] Ismerőseid,Ismerőseid. Ó, On App Engine after install/run : I 2012-12-21 06:52:07.730 É, Á, Ö, Ü. Ó, E 2012-12-21 06:52:07.736 Traceback (most recent call last): File "....", line 672, in xxxx s3 = s1 + u':' + s1 UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128) I have tried to various combination of encoding/decoding/etc.. I have also chardet on the pasted string 'Ismerőseid' and it gives me `{'confidence': 0.7402600692642154, 'encoding': 'ISO-8859-2'}` Any help is greatly appreciated! Answer: Put these 3 lines on the top of your Python 27 code to use unicode : #!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import unicode_literals # And this code will not give you any problems s1 = 'É, Á, Ö, Ü. Ó,' logging.info (s1) s2 = s1 + ':' + s1 logging.info ("%s,%s", s1, s2) And never user str(). Only if you realy need to! And read [this blogpost](http://blog.notdot.net/2010/07/Getting-unicode-right- in-Python) from Nick Johnson. This was before Python 27. He did not use the `from __future__ import unicode_literals` , which makes using unicode with Python so easy.
import error when I test scikit on ubuntu12.04 Question: I want to install scikit on ubuntu12.04 and I followed the instruction on [the official installing documentation](http://scikit- learn.org/stable/install.html)and type the following command in the bash: sudo apt-get install python-sklearn next I type the test instruction nosetests sklearn --exe But I got many import errors! I searched google but found little useful links. I'm new to python and I want to learn python and machine learning through scikit.So please help me, thank you. Below are the error information when I run the nosetests command in bash.Due to the length limitation, I deleted some error. EEEEEE..............EE.....EE........EE.............EEE......EE.......... ====================================================================== ERROR: Failure: ImportError (No module named joblib) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/loader.py", line 390, in loadTestsFromName addr.filename, addr.module) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 39, in importFromPath return self.importFromDir(dir_path, fqname) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 86, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/usr/lib/pymodules/python2.7/sklearn/cluster/__init__.py", line 10, in <module> from .hierarchical import ward_tree, Ward, WardAgglomeration File "/usr/lib/pymodules/python2.7/sklearn/cluster/hierarchical.py", line 20, in <module> from ..externals.joblib import Memory File "/usr/lib/pymodules/python2.7/sklearn/externals/joblib/__init__.py", line 3, in <module> from joblib import * ImportError: No module named joblib ====================================================================== ERROR: Failure: ImportError (No module named joblib) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/loader.py", line 390, in loadTestsFromName addr.filename, addr.module) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 39, in importFromPath return self.importFromDir(dir_path, fqname) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 86, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/usr/lib/pymodules/python2.7/sklearn/covariance/__init__.py", line 14, in <module> from .graph_lasso_ import graph_lasso, GraphLasso, GraphLassoCV File "/usr/lib/pymodules/python2.7/sklearn/covariance/graph_lasso_.py", line 20, in <module> from ..linear_model import lars_path File "/usr/lib/pymodules/python2.7/sklearn/linear_model/__init__.py", line 16, in <module> from .least_angle import Lars, LassoLars, lars_path, LARS, LassoLARS, \ File "/usr/lib/pymodules/python2.7/sklearn/linear_model/least_angle.py", line 19, in <module> from ..cross_validation import check_cv File "/usr/lib/pymodules/python2.7/sklearn/cross_validation.py", line 21, in <module> from .externals.joblib import Parallel, delayed File "/usr/lib/pymodules/python2.7/sklearn/externals/joblib/__init__.py", line 3, in <module> from joblib import * ImportError: No module named joblib ====================================================================== ERROR: Failure: ImportError (No module named joblib) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/loader.py", line 390, in loadTestsFromName addr.filename, addr.module) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 39, in importFromPath return self.importFromDir(dir_path, fqname) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 86, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/usr/lib/pymodules/python2.7/sklearn/datasets/__init__.py", line 18, in <module> from .lfw import load_lfw_pairs File "/usr/lib/pymodules/python2.7/sklearn/datasets/lfw.py", line 34, in <module> from ..externals.joblib import Memory File "/usr/lib/pymodules/python2.7/sklearn/externals/joblib/__init__.py", line 3, in <module> from joblib import * ImportError: No module named joblib ====================================================================== ERROR: Failure: ImportError (No module named joblib) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/loader.py", line 390, in loadTestsFromName addr.filename, addr.module) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 39, in importFromPath return self.importFromDir(dir_path, fqname) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 86, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/usr/lib/pymodules/python2.7/sklearn/externals/joblib/__init__.py", line 3, in <module> from joblib import * ImportError: No module named joblib ====================================================================== ERROR: Failure: ImportError (cannot import name Parallel) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/loader.py", line 390, in loadTestsFromName addr.filename, addr.module) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 39, in importFromPath return self.importFromDir(dir_path, fqname) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 86, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/usr/lib/pymodules/python2.7/sklearn/feature_extraction/tests/test_text.py", line 10, in <module> from sklearn.grid_search import GridSearchCV File "/usr/lib/pymodules/python2.7/sklearn/grid_search.py", line 18, in <module> from .cross_validation import check_cv File "/usr/lib/pymodules/python2.7/sklearn/cross_validation.py", line 21, in <module> from .externals.joblib import Parallel, delayed ImportError: cannot import name Parallel ====================================================================== ERROR: Failure: ImportError (cannot import name Parallel) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/loader.py", line 390, in loadTestsFromName addr.filename, addr.module) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 39, in importFromPath return self.importFromDir(dir_path, fqname) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 86, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/usr/lib/pymodules/python2.7/sklearn/feature_selection/__init__.py", line 17, in <module> from .rfe import RFE File "/usr/lib/pymodules/python2.7/sklearn/feature_selection/rfe.py", line 13, in <module> from ..cross_validation import check_cv File "/usr/lib/pymodules/python2.7/sklearn/cross_validation.py", line 21, in <module> from .externals.joblib import Parallel, delayed ImportError: cannot import name Parallel ====================================================================== ERROR: Failure: ImportError (cannot import name Parallel) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/loader.py", line 390, in loadTestsFromName addr.filename, addr.module) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 39, in importFromPath return self.importFromDir(dir_path, fqname) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 86, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/usr/lib/pymodules/python2.7/sklearn/linear_model/__init__.py", line 16, in <module> from .least_angle import Lars, LassoLars, lars_path, LARS, LassoLARS, \ File "/usr/lib/pymodules/python2.7/sklearn/linear_model/least_angle.py", line 19, in <module> from ..cross_validation import check_cv File "/usr/lib/pymodules/python2.7/sklearn/cross_validation.py", line 21, in <module> from .externals.joblib import Parallel, delayed ImportError: cannot import name Parallel ====================================================================== ERROR: Failure: ImportError (cannot import name Memory) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/loader.py", line 390, in loadTestsFromName addr.filename, addr.module) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 39, in importFromPath return self.importFromDir(dir_path, fqname) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 86, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/usr/lib/pymodules/python2.7/sklearn/metrics/cluster/tests/test_unsupervised.py", line 3, in <module> from .... import datasets File "/usr/lib/pymodules/python2.7/sklearn/datasets/__init__.py", line 18, in <module> from .lfw import load_lfw_pairs File "/usr/lib/pymodules/python2.7/sklearn/datasets/lfw.py", line 34, in <module> from ..externals.joblib import Memory ImportError: cannot import name Memory ====================================================================== ERROR: Failure: ImportError (cannot import name Memory) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/loader.py", line 390, in loadTestsFromName addr.filename, addr.module) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 39, in importFromPath return self.importFromDir(dir_path, fqname) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 86, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/usr/lib/pymodules/python2.7/sklearn/metrics/tests/test_metrics.py", line 10, in <module> from ... import datasets File "/usr/lib/pymodules/python2.7/sklearn/datasets/__init__.py", line 18, in <module> from .lfw import load_lfw_pairs File "/usr/lib/pymodules/python2.7/sklearn/datasets/lfw.py", line 34, in <module> from ..externals.joblib import Memory ImportError: cannot import name Memory ====================================================================== ERROR: Failure: ImportError (cannot import name Memory) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/loader.py", line 390, in loadTestsFromName addr.filename, addr.module) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 39, in importFromPath return self.importFromDir(dir_path, fqname) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 86, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/usr/lib/pymodules/python2.7/sklearn/utils/tests/test_sparsefuncs.py", line 5, in <module> from sklearn.datasets import make_classification File "/usr/lib/pymodules/python2.7/sklearn/datasets/__init__.py", line 18, in <module> from .lfw import load_lfw_pairs File "/usr/lib/pymodules/python2.7/sklearn/datasets/lfw.py", line 34, in <module> from ..externals.joblib import Memory ImportError: cannot import name Memory ====================================================================== ERROR: Failure: ImportError (cannot import name Memory) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/loader.py", line 390, in loadTestsFromName addr.filename, addr.module) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 39, in importFromPath return self.importFromDir(dir_path, fqname) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 86, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/usr/lib/pymodules/python2.7/sklearn/utils/tests/test_svd.py", line 12, in <module> from sklearn.datasets.samples_generator import make_low_rank_matrix File "/usr/lib/pymodules/python2.7/sklearn/datasets/__init__.py", line 18, in <module> from .lfw import load_lfw_pairs File "/usr/lib/pymodules/python2.7/sklearn/datasets/lfw.py", line 34, in <module> from ..externals.joblib import Memory ImportError: cannot import name Memory ====================================================================== ERROR: Tests that clone creates a correct deep copy. ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/case.py", line 197, in runTest self.test(*self.arg) File "/usr/lib/pymodules/python2.7/sklearn/tests/test_base.py", line 48, in test_clone from sklearn.feature_selection import SelectFpr, f_classif File "/usr/lib/pymodules/python2.7/sklearn/feature_selection/__init__.py", line 17, in <module> from .rfe import RFE File "/usr/lib/pymodules/python2.7/sklearn/feature_selection/rfe.py", line 13, in <module> from ..cross_validation import check_cv File "/usr/lib/pymodules/python2.7/sklearn/cross_validation.py", line 21, in <module> from .externals.joblib import Parallel, delayed ImportError: cannot import name Parallel ====================================================================== ERROR: Tests that clone doesn't copy everything. ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/case.py", line 197, in runTest self.test(*self.arg) File "/usr/lib/pymodules/python2.7/sklearn/tests/test_base.py", line 64, in test_clone_2 from sklearn.feature_selection import SelectFpr, f_classif File "/usr/lib/pymodules/python2.7/sklearn/feature_selection/__init__.py", line 17, in <module> from .rfe import RFE File "/usr/lib/pymodules/python2.7/sklearn/feature_selection/rfe.py", line 13, in <module> from ..cross_validation import check_cv File "/usr/lib/pymodules/python2.7/sklearn/cross_validation.py", line 21, in <module> from .externals.joblib import Parallel, delayed ImportError: cannot import name Parallel ====================================================================== ERROR: sklearn.tests.test_base.test_is_classifier ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/case.py", line 197, in runTest self.test(*self.arg) File "/usr/lib/pymodules/python2.7/sklearn/tests/test_base.py", line 109, in test_is_classifier from ..svm import SVC File "/usr/lib/pymodules/python2.7/sklearn/svm/__init__.py", line 13, in <module> from .classes import SVC, NuSVC, SVR, NuSVR, OneClassSVM, LinearSVC File "/usr/lib/pymodules/python2.7/sklearn/svm/classes.py", line 2, in <module> from ..linear_model.base import CoefSelectTransformerMixin File "/usr/lib/pymodules/python2.7/sklearn/linear_model/__init__.py", line 16, in <module> from .least_angle import Lars, LassoLars, lars_path, LARS, LassoLARS, \ File "/usr/lib/pymodules/python2.7/sklearn/linear_model/least_angle.py", line 19, in <module> from ..cross_validation import check_cv File "/usr/lib/pymodules/python2.7/sklearn/cross_validation.py", line 21, in <module> from .externals.joblib import Parallel, delayed ImportError: cannot import name Parallel ====================================================================== ERROR: Failure: ImportError (cannot import name Memory) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/loader.py", line 390, in loadTestsFromName addr.filename, addr.module) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 39, in importFromPath return self.importFromDir(dir_path, fqname) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 86, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/usr/lib/pymodules/python2.7/sklearn/tests/test_cross_validation.py", line 10, in <module> from ..datasets import make_regression File "/usr/lib/pymodules/python2.7/sklearn/datasets/__init__.py", line 18, in <module> from .lfw import load_lfw_pairs File "/usr/lib/pymodules/python2.7/sklearn/datasets/lfw.py", line 34, in <module> from ..externals.joblib import Memory ImportError: cannot import name Memory ====================================================================== ERROR: Failure: ImportError (cannot import name Parallel) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/loader.py", line 390, in loadTestsFromName addr.filename, addr.module) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 39, in importFromPath return self.importFromDir(dir_path, fqname) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 86, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/usr/lib/pymodules/python2.7/sklearn/tests/test_grid_search.py", line 12, in <module> from sklearn.grid_search import GridSearchCV File "/usr/lib/pymodules/python2.7/sklearn/grid_search.py", line 18, in <module> from .cross_validation import check_cv File "/usr/lib/pymodules/python2.7/sklearn/cross_validation.py", line 21, in <module> from .externals.joblib import Parallel, delayed ImportError: cannot import name Parallel ====================================================================== ERROR: Failure: ImportError (cannot import name Memory) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/loader.py", line 390, in loadTestsFromName addr.filename, addr.module) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 39, in importFromPath return self.importFromDir(dir_path, fqname) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 86, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/usr/lib/pymodules/python2.7/sklearn/tests/test_hmm.py", line 6, in <module> from sklearn.datasets.samples_generator import make_spd_matrix File "/usr/lib/pymodules/python2.7/sklearn/datasets/__init__.py", line 18, in <module> from .lfw import load_lfw_pairs File "/usr/lib/pymodules/python2.7/sklearn/datasets/lfw.py", line 34, in <module> from ..externals.joblib import Memory ImportError: cannot import name Memory ====================================================================== ERROR: Failure: ImportError (cannot import name Parallel) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/loader.py", line 390, in loadTestsFromName addr.filename, addr.module) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 39, in importFromPath return self.importFromDir(dir_path, fqname) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 86, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/usr/lib/pymodules/python2.7/sklearn/tests/test_multiclass.py", line 13, in <module> from sklearn.svm import LinearSVC File "/usr/lib/pymodules/python2.7/sklearn/svm/__init__.py", line 13, in <module> from .classes import SVC, NuSVC, SVR, NuSVR, OneClassSVM, LinearSVC File "/usr/lib/pymodules/python2.7/sklearn/svm/classes.py", line 2, in <module> from ..linear_model.base import CoefSelectTransformerMixin File "/usr/lib/pymodules/python2.7/sklearn/linear_model/__init__.py", line 16, in <module> from .least_angle import Lars, LassoLars, lars_path, LARS, LassoLARS, \ File "/usr/lib/pymodules/python2.7/sklearn/linear_model/least_angle.py", line 19, in <module> from ..cross_validation import check_cv File "/usr/lib/pymodules/python2.7/sklearn/cross_validation.py", line 21, in <module> from .externals.joblib import Parallel, delayed ImportError: cannot import name Parallel ====================================================================== ERROR: Failure: ImportError (cannot import name Parallel) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/loader.py", line 390, in loadTestsFromName addr.filename, addr.module) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 39, in importFromPath return self.importFromDir(dir_path, fqname) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 86, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/usr/lib/pymodules/python2.7/sklearn/tests/test_pipeline.py", line 9, in <module> from ..svm import SVC File "/usr/lib/pymodules/python2.7/sklearn/svm/__init__.py", line 13, in <module> from .classes import SVC, NuSVC, SVR, NuSVR, OneClassSVM, LinearSVC File "/usr/lib/pymodules/python2.7/sklearn/svm/classes.py", line 2, in <module> from ..linear_model.base import CoefSelectTransformerMixin File "/usr/lib/pymodules/python2.7/sklearn/linear_model/__init__.py", line 16, in <module> from .least_angle import Lars, LassoLars, lars_path, LARS, LassoLARS, \ File "/usr/lib/pymodules/python2.7/sklearn/linear_model/least_angle.py", line 19, in <module> from ..cross_validation import check_cv File "/usr/lib/pymodules/python2.7/sklearn/cross_validation.py", line 21, in <module> from .externals.joblib import Parallel, delayed ImportError: cannot import name Parallel ====================================================================== ERROR: Failure: ImportError (cannot import name Memory) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/loader.py", line 390, in loadTestsFromName addr.filename, addr.module) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 39, in importFromPath return self.importFromDir(dir_path, fqname) File "/usr/lib/python2.7/dist-packages/nose/importer.py", line 86, in importFromDir mod = load_module(part_fqname, fh, filename, desc) File "/usr/lib/pymodules/python2.7/sklearn/tests/test_pls.py", line 3, in <module> from sklearn.datasets import load_linnerud File "/usr/lib/pymodules/python2.7/sklearn/datasets/__init__.py", line 18, in <module> from .lfw import load_lfw_pairs File "/usr/lib/pymodules/python2.7/sklearn/datasets/lfw.py", line 34, in <module> from ..externals.joblib import Memory ImportError: cannot import name Memory ====================================================================== FAIL: Test either above import has failed for some reason ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/nose/case.py", line 197, in runTest self.test(*self.arg) File "/usr/lib/pymodules/python2.7/sklearn/tests/test_init.py", line 22, in test_import_skl assert_equal(_top_import_error, None) AssertionError: ImportError('cannot import name Parallel',) != None ---------------------------------------------------------------------- Ran 100 tests in 6.478s FAILED (errors=26, failures=1) Answer: Check if the `python-joblib` package is installed sudo dpkg -l | grep joblib If nothing is returned, try running apt-cache search joblib there should be a package named `python-joblib`: install it using sudo apt-get install python-joblib and retry. **EDIT** : You are right, that package is installed, but Python seems unable to find it (proved by your `import joblib` fail). Normally this means that the path where the package has been installed is not part of the Python's search path. What you can do is either manually install the module from the source and specify the path (which seems to be `/usr/lib/python2.7`), or use a tool such as `easy_install` or `pip` to do that for you. As stated in your guide, `pip install -U scikit-learn` or `easy_install -U scikit-learn` should do the trick for you, since your libraries are already there...
No valid context when using glutMouseFunc in python Question: I'm trying to write program in Python using PyOpenGL which I need to use glutMouseFunc for some mouse functionality but when I run the program I get the following error: Traceback (most recent call last): File "teapot.py", line 80, in <module> glutMouseFunc(mouseHandle) File "/usr/lib/python2.7/dist-packages/OpenGL/GLUT/special.py", line 137, in __call__ contextdata.setValue( self.CONTEXT_DATA_KEY, cCallback ) File "/usr/lib/python2.7/dist-packages/OpenGL/contextdata.py", line 57, in setValue context = getContext( context ) File "/usr/lib/python2.7/dist-packages/OpenGL/contextdata.py", line 40, in getContext """Attempt to retrieve context when no valid context""" OpenGL.error.Error: Attempt to retrieve context when no valid context I tried googling it but I couldn't find any related result.Here is my code: from OpenGL.GL import * from OpenGL.GLUT import * t = 0 def init(): r=1 g=0 b=0 glColor3f(r,g,b) glClearColor(1.0,1.0,1.0,0.0) glMatrixMode(GL_PROJECTION) glLoadIdentity() def display(): glClear(GL_COLOR_BUFFER_BIT) glViewport(0,0,150,100) drawSquare() glViewport(0,100,150,200) drawCircle() glViewport(0,200,150,300) drawTriangle() glViewport(0,300,150,400) drawFan() if(t==1): glViewport(150,0,800,600) drawFan() if(t==2): glViewport(150,0,800,600) drawTriangle() if(t==3): glViewport(150,0,800,600) drawCircle() if(t==4): glViewport(150,0,800,600) drawSquare() glFlush() def drawFan(): glBegin(GL_TRIANGLE_FAN) glVertex2f(0.0,0.0) glVertex2f(0.3,0.3) glVertex2f(0.3,-0.3) glVertex2f(-0.3,0.3) glVertex2f(-0.3,-0.3) glEnd() def drawTriangle(): glBegin(GL_TRIANGLES) glVertex2f(0.5,0.0) glVertex2f(0.0,0.5) glVertex2f(-0.5,0.0) glEnd() def drawCircle(): glutSolidSphere(0.5, 30 ,30) def drawSquare(): glBegin(GL_POLYGON) glVertex2f(0.5,0.5) glVertex2f(-0.5,0.5) glVertex2f(-0.5,-0.5) glVertex2f(0.5,-0.5) glEnd() def mouseHandle(button, state, x, y): if(button == GLUT_LEFT_BUTTON and x < 150 and y < 170): t=1 glutPostRedisplay() print "1: x=",x," y=",y,"\n" elif(button == GLUT_LEFT_BUTTON and x < 150 and 170 < y and y < 280): t=2 glutPostRedisplay() elif(button == GLUT_LEFT_BUTTON and x < 150 and 345 < y and y < 451): t=3 glutPostRedisplay() elif(button == GLUT_LEFT_BUTTON and x < 150 and 525 < y and y < 578): t=4 glutPostRedisplay() else: glutPostRedisplay() glutInit('') glutMouseFunc(mouseHandle) glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB) glutInitWindowSize(800,600) glutCreateWindow('Hello GLUT') glutDisplayFunc(display) init() glutMainLoop() Answer: Ok, after some dwelling I found out how to solve it. I must've moved the `glutMouseFunc` call after `glutDisplayFunc`, just like below: glutInit('') glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB) glutInitWindowSize(800,600) glutCreateWindow('Hello GLUT') glutDisplayFunc(display) glutMouseFunc(mouseHandle) init() glutMainLoop()
How to confirm only html files exist in a given folder and if not then how to prompt the user to specify a folder with only html files within Question: I would like to create a python script that will do 3 things: * 1) Take user input to navigate to a file directory * 2) Confirm the file contents (a particular set of files need to be in the folder for the script to proceed) * 3) Do a Find and Replace The Code as of now: import os, time from os.path import walk mydictionary = {"</i>":"</em>"} for (path, dirs, files) in os.walk(raw_input('Copy and Paste Course Directory Here: ')): for f in files: if f.endswith('.html'): filepath = os.path.join(path,f) s = open(filepath).read() for k, v in mydictionary.iteritems(): terms for a dictionary file and replace s = s.replace(k, v) f = open(filepath, 'w') f.write(s) f.close() Now i Have parts 1 and 3, I just need part 2. for part 2 though I need to confirm that only html files exist in the directory the the user will specified otherwise the script will prompt the user to enter the correct folder directory (which will contain html files) Thanks Answer: From what I understand, here's your pseudocode: Ask user for directory If all files in that directory are .html files: Do the search-and-replace stuff on the files Else: Warn and repeat from start I don't think you actually want a recursive walk here, so first I'll write that with a flat listing: while True: dir = raw_input('Copy and Paste Course Directory Here: ') files = os.listdir(dir) if all(file.endswith('.html') for file in files): # do the search and replace stuff break else: print 'Sorry, there are non-HTML files here. Try again.' Except for having the translate the "repeat from start" into a `while True` loop with a `break`, this is almost a word-for-word translation from the English pseudocode. If you _do_ need the recursive walk through subdirectories, you probably don't want to write the `all` as a one-liner. It's not that hard to write "all members of the third member of any member of the `os.walk` result end with `'.html'`", but it will be hard to read. But if you turn that English description into something more understandable, you should be able to see how to turn it directly into code.
Tkinter and pyplot running out of memory Question: I'm running a Tkinter script that updates a plot every 5 seconds. It calls the function that plots it every 5 seconds. After not that long python starts using a lot of memory, I checked in task manager. The memory usage keeps increasing really fast. It starts a new file every 24 hours so there is a limit to the number of lines in the file. The file starts empty. I tried increasing the 5s time span but it does the same thing. Maybe a little slower, also tried tried plotting every 3 rows or so but the same thing happened again. Any idea what is causing such high memory usage and how to fix? Thanks! data = np.genfromtxt(filename) time_data = data[:,0] room_temp_data_celsius = data[:,1] rad_temp_data_celsius = data[:,2] fan_state_data = data[:,3] threshold_data = data[:,4] hysteresis_data = data[:,5] threshold_up = [] #empty array threshold_down = []#empty array for i in range(0,len(threshold_data)): threshold_up.append(threshold_data[i]+hysteresis_data[i]) threshold_down.append(threshold_data[i]-hysteresis_data[i]) # Time formatting dts = map(datetime.datetime.fromtimestamp, time_data) fds = matplotlib.dates.date2num(dts) hfmt = matplotlib.dates.DateFormatter('%H:%M') # Temperature conversion room_temp_data_fahrenheit = map(celsius_to_fahrenheit, room_temp_data_celsius) rad_temp_data_fahrenheit = map(celsius_to_fahrenheit, rad_temp_data_celsius) threshold_data_fahrenheit = map(celsius_to_fahrenheit, threshold_data) threshold_up_fahrenheit = map(celsius_to_fahrenheit, threshold_up) threshold_down_fahrenheit = map(celsius_to_fahrenheit, threshold_down) f = plt.figure() a = f.add_subplot(111) a.plot(fds,room_temp_data_fahrenheit, fds, rad_temp_data_fahrenheit, 'r') a.plot(fds,fan_state_data*(max(rad_temp_data_fahrenheit)+4),'g_') a.plot(fds, threshold_up_fahrenheit, 'y--') a.plot(fds, threshold_down_fahrenheit, 'y--') plt.xlabel('Time (min)') plt.ylabel('Temperature '+unichr(176)+'F') plt.legend(["Room Temperature","Radiator","Fan State","Threshold Region"], loc="upper center", ncol=2) plt.ylim([min(room_temp_data_fahrenheit)-5, max(rad_temp_data_fahrenheit)+5]) plt.grid() a.xaxis.set_major_formatter(hfmt) data_graph = FigureCanvasTkAgg(f, master=root) data_graph.show() data_graph.get_tk_widget().grid(row=6,column=0, columnspan=3) root.after(WAIT_TIME, control) Answer: It's not clear to me from your code how your plots are changing with time. So I don't have any specific suggestion for your existing code. However, here is a basic example of how to embed an animated matplotlib figure in a Tkinter app. Once you grok how it works, you should be able to adapt it to your situation. import matplotlib.pyplot as plt import numpy as np import Tkinter as tk import matplotlib.figure as mplfig import matplotlib.backends.backend_tkagg as tkagg pi = np.pi sin = np.sin class App(object): def __init__(self, master): self.master = master self.fig = mplfig.Figure(figsize = (5, 4), dpi = 100) self.ax = self.fig.add_subplot(111) self.canvas = canvas = tkagg.FigureCanvasTkAgg(self.fig, master) canvas.get_tk_widget().pack(side = tk.TOP, fill = tk.BOTH, expand = 1) self.toolbar = toolbar = tkagg.NavigationToolbar2TkAgg(canvas, master) toolbar.update() self.update = self.animate().next master.after(10, self.update) canvas.show() def animate(self): x = np.linspace(0, 6*pi, 100) y = sin(x) line1, = self.ax.plot(x, y, 'r-') phase = 0 while True: phase += 0.1 line1.set_ydata(sin(x + phase)) newx = x+phase line1.set_xdata(newx) self.ax.set_xlim(newx.min(), newx.max()) self.ax.relim() self.ax.autoscale_view(True, True, True) self.fig.canvas.draw() self.master.after(10, self.update) yield def main(): root = tk.Tk() app = App(root) tk.mainloop() if __name__ == '__main__': main() * * * The main idea here is that `plt.plot` should only be called once. It returns a `Line2D` object, `line1`. You can then manipulate the plot by calling `line1.set_xdata` and/or `line1.set_ydata`. This "technique" for animation comes from the [Matplotlib Cookbook](http://www.scipy.org/Cookbook/Matplotlib/Animations). Technical note: The generator function, `animate` was used here to allow the state of the plot to be saved and updated without having to save state information in instance attributes. Note that it is the generator function's `next` method (not the generator `self.animate`) which is being called repeatedly: self.update = self.animate().next master.after(10, self.update) So we are advancing the plot frame-by-frame by calling the generator, `self.animate()`'s, next method.
Is there a way to invoke a leftclick in python? Question: I only have the python 2.6. Can I do this without using external libraries? I just want to perform a left click wherever the cursor currently is. Answer: OK, first you have to know how to open the user32 windll via `ctypes`, which is [trivial](http://docs.python.org/2/library/ctypes.html#loading-dynamic- link-libraries): from ctypes import * user32 = windll.user32 Next, the Win32 function you want to call is probably [SendInput](http://msdn.microsoft.com/en- us/library/windows/desktop/ms646310%28v=vs.85%29.aspx), although you might want to look at `mouse_event` and possibly `SendMessage` (and the documentation for which WM_* messages correspond to a mouse click) to compare and contrast. Assuming you go with `SendInput`, you're going to send one `MOUSEEVENTF_LEFTDOWN` followed by one `MOUSEEVENTF_LEFTUP`, with 0 for all of the params besides `dwFlags`. So, how do you call this? Well, here's the C API: UINT WINAPI SendInput( _In_ UINT nInputs, _In_ LPINPUT pInputs, _In_ int cbSize ); That `LPINPUT` means you've got a pointer to an array of [`INPUT`](http://msdn.microsoft.com/en- us/library/windows/desktop/ms646270%28v=vs.85%29.aspx) structures. Since the `INPUT` structure itself has a union of `MOUSEINPUT`, `KBDINPUT`, and `HARDWAREINPUT`, you'll also need to define those (although you can get away with just defining the first and pretending the others don't exist, since the first is the only one you need). So, the steps to doing this with `ctypes` are: * Define the [`Structure`](http://docs.python.org/2/library/ctypes.html#structures-and-unions)s for [`MOUSEINPUT`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms646273%28v=vs.85%29.aspx) and [`INPUT`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms646270%28v=vs.85%29.aspx). * Load the `user32` windll. * Set the [`argtypes`](http://docs.python.org/2/library/ctypes.html#specifying-the-required-argument-types-function-prototypes) for `user32.SendInput`. * Create your first `MOUSEINPUT` instance, with `dwFlags= MOUSEEVENTF_LEFTDOWN`, and the `INPUT` instance to go with it. * Call `user32.SendInput(1, [myinput], len(INPUT))` or `user32.SendInput(1, addressof(myinput), len(INPUT))` or whatever (depending on how you defined the `argtypes`). * Create your second `MOUSEINPUT` instance, with `dwFlags= MOUSEEVENTF_LEFT`, and the `INPUT` instance to go with it. * Call `user32.SendInput()` again. One last note: On Vista and above, you have to have the right "integrity level" to do this. For example, a normal app cannot send a click to an "elevated" app (e.g., an installer). Hopefully this isn't an issue for you. If it is, you need to read up on UIPI and UAC… and if worst comes to worst, you may need to fall back to lower-level tricks. Is that enough, or do you need help with some specific part of this?
Python extract data from file and write to another Question: I'm new in python and need help. I have a file and want to extract text to another file. The input file looks like this: <Datei Kennung="4bc78" Titel="Morgen 1" Bereich="I847YP"> Morgen 1 Here is text, contains numbers and text. Here is text, contains numbers and text. Here is text, contains numbers and text. Here is text, contains numbers and text. Here is text, contains numbers and text. </Datei> <Datei Kennung="469" Titel="Trop Hall W " Bereich="izr"> Trop Hall W Here is text, contains numbers and text. Here is text, contains numbers and text. </Datei> For the first area in my file i need as output the file Morgen 1.txt which contains this: Morgen 1 Here is text, contains numbers and text. Here is text, contains numbers and text. Here is text, contains numbers and text. Here is text, contains numbers and text. Here is text, contains numbers and text. I got from other user this code: import re REG_PARSE=re.compile(r'<Datei[^>]*Titel="\s*([^"]*?)\s*"[^>]*>\s*\1\s*(.*?</Datei>',re.dotall) with open(filename) as infile: for outfilename, text = REG_PARSE.finditer(infile.read()): with open('%s.txt'%outfilename,'w') as outf: outf.write(text) but it does not work Answer: See if this works for you: #!/usr/bin/env python #-*- coding:utf-8 -*- from xml.dom import minidom xmldoc = minidom.parse('/path/to/file') items = xmldoc.getElementsByTagName('Datei') for s in items: if s.attributes['Titel'].value == "Morgen 1": with open("Morgen 1.txt", "w") as fileOutput: listLines = [ line.strip() for line in s.firstChild.nodeValue.strip().split("\n") if line.strip() ] fileOutput.write("\n".join(listLines)) break
2D and 3D Scatter Histograms from arrays in Python Question: have you any idea, how I can bin 3 arrays to a histogram. My arrays look like Temperature = [4, 3, 1, 4, 6, 7, 8, 3, 1] Radius = [0, 2, 3, 4, 0, 1, 2, 10, 7] Density = [1, 10, 2, 24, 7, 10, 21, 102, 203] And the 1D plot should look: Density | X 10^2-| X | X 10^1-| | X 10^0-| |___|___|___|___|___ Radius 0 3.3 6.6 10 And the 2D plot should (qualitative) look like: Density | 2 | | 10^2-| 11249 | | | 233 | | Radius 10^1-| 12 | | | 1 | | 10^0-| |___|___|___|___|___ Temperature 0 3 5 8 So I want to bin one or two fields with python/numpy and then plot them to analyse their correspondence. Answer: Here it follows two functions: `hist2d_bubble` and `hist3d_bubble`; that may fit for your purpose: ![enter image description here](http://i.stack.imgur.com/48K32.png) def hist2d_bubble(x_data, y_data, bins=10): import numpy as np import matplotlib.pyplot as pyplot ax = np.histogram2d(x_data, y_data, bins=bins) xs = ax[1] dx = xs[1] - xs[0] ys = ax[2] dy = ys[1] - ys[0] def rdn(): return (1-(-1))*np.random.random() + -1 points = [] for (i, j),v in np.ndenumerate(ax[0]): points.append((xs[i], ys[j], v)) points = np.array(points) fig = pyplot.figure() sub = pyplot.scatter(points[:, 0],points[:, 1], color='black', marker='o', s=128*points[:, 2]) sub.axes.set_xticks(xs) sub.axes.set_yticks(ys) pyplot.ion() pyplot.grid() pyplot.show() return points, sub def hist3d_bubble(x_data, y_data, z_data, bins=10): import numpy as np import matplotlib.pyplot as pyplot from mpl_toolkits.mplot3d import Axes3D ax1 = np.histogram2d(x_data, y_data, bins=bins) ax2 = np.histogram2d(x_data, z_data, bins=bins) ax3 = np.histogram2d(z_data, y_data, bins=bins) xs, ys, zs = ax1[1], ax1[2], ax3[1] dx, dy, dz = xs[1]-xs[0], ys[1]-ys[0], zs[1]-zs[0] def rdn(): return (1-(-1))*np.random.random() + -1 smart = np.zeros((bins, bins, bins),dtype=int) for (i1, j1), v1 in np.ndenumerate(ax1[0]): if v1==0: continue for k2, v2 in enumerate(ax2[0][i1]): v3 = ax3[0][k2][j1] if v1==0 or v2==0 or v3==0: continue num = min(v1, v2, v3) smart[i1, j1, k2] += num v1 -= num v2 -= num v3 -= num points = [] for (i,j,k),v in np.ndenumerate(smart): points.append((xs[i], ys[j], zs[k], v)) points = np.array(points) fig = pyplot.figure() sub = fig.add_subplot(111, projection='3d') sub.scatter(points[:, 0], points[:, 1], points[:, 2], color='black', marker='o', s=128*points[:, 3]) sub.axes.set_xticks(xs) sub.axes.set_yticks(ys) sub.axes.set_zticks(zs) pyplot.ion() pyplot.grid() pyplot.show() return points, sub The two figures above were created using: temperature = [4, 3, 1, 4, 6, 7, 8, 3, 1] radius = [0, 2, 3, 4, 0, 1, 2, 10, 7] density = [1, 10, 2, 24, 7, 10, 21, 102, 203] import matplotlib matplotlib.rcParams.update({'font.size':14}) points, sub = hist2d_bubble(radius, density, bins=4) sub.axes.set_xlabel('radius') sub.axes.set_ylabel('density') points, sub = hist3d_bubble(temperature, density, radius, bins=4) sub.axes.set_xlabel('temperature') sub.axes.set_ylabel('density') sub.axes.set_zlabel('radius') Related: [Howto bin series of float values into histogram in Python?](http://stackoverflow.com/questions/1721273/howto-bin-series-of-float- values-into-histogram-in-python) [How to correctly generate a 3d histogram using numpy or matplotlib built in functions in python?](http://stackoverflow.com/questions/8437788/how-to- correctly-generate-a-3d-histogram-using-numpy-or-matplotlib-built-in-func) [2D histogram with Python](http://stackoverflow.com/questions/6832168/2d-histogram-with-python)
fft in python not showing peaks in right place Question: I'm trying to understand the numpy fft function, because my data reduction is acting weirdly. But now that I've transformed a simple sum of two sines, I get weird results. The peaks I have is extremely high and several points wide around zero, flattening the rest. Does anybody have a clue of what I might be doing wrong? import numpy as np from numpy import exp, sqrt, pi, linspace from matplotlib import cm import matplotlib.pyplot as plt import scipy as sp import pylab #fourier tdata = np.arange(5999.)/300 datay = 3*np.sin(tdata)+6*np.sin(2*tdata) fouriery = np.fft.fft(datay) freqs = np.fft.fftfreq(datay.size, d=0.1) pylab.plot(freqs,fouriery) pylab.show() What I get is this: ![enter image description here](http://i.stack.imgur.com/LiUu4.png) While it should have two sidepeaks on both sides, one of em 2x higher than the other Answer: * Your `datay` is real, so perhaps you should be taking a FFT for a real sequence using `scipy.fftpack.rfft`. * If you are looking for an FFT with two distinct peaks, then you must give it data which is the sum of sine waves whose terms have periods which are whole multiples of `2*pi/n`, where `n = len(datay)`. If not, it will take many such sine waves to approximate the data. * * * import numpy as np import matplotlib.pyplot as plt import scipy.fftpack as fftpack pi = np.pi tdata = np.arange(5999.)/300 datay = 3*np.sin(2*pi*tdata)+6*np.sin(2*pi*2*tdata) fouriery = fftpack.rfft(datay) freqs = fftpack.rfftfreq(len(datay), d=(tdata[1]-tdata[0])) plt.plot(freqs, fouriery, 'b-') plt.xlim(0,3) plt.show() ![enter image description here](http://i.stack.imgur.com/JffGU.png)
How to use malt parser in python nltk Question: As a part of my academic project I need to parse a bunch of arbitrary sentences into a dependency graph. After a searching a lot I got the solution that I can use Malt Parser for parsing text with its pre trained grammer. I have downloaded pre-trained model (engmalt.linear-1.7.mco) from <http://www.maltparser.org/mco/mco.html>. BUt I don't know how to parse my sentences using this grammer file and malt parser (by the python interface for malt). I have downloaded latest version of malt parser (1.7.2) and moved it to '/usr/lib/' import nltk; parser =nltk.parse.malt.MaltParser() txt="This is a test sentence" parser.train_from_file('/home/rohith/malt-1.7.2/engmalt.linear-1.7.mco') parser.raw_parse(txt) after executing the last line the following eror message is dispalyed Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> parser.raw_parse(txt) File "/usr/local/lib/python2.7/dist-packages/nltk-2.0b5-py2.7.egg/nltk/parse/malt.py", line 88, in raw_parse return self.parse(words, verbose) File "/usr/local/lib/python2.7/dist-packages/nltk-2.0b5-py2.7.egg/nltk/parse/malt.py", line 75, in parse return self.tagged_parse(taggedwords, verbose) File "/usr/local/lib/python2.7/dist-packages/nltk-2.0b5-py2.7.egg/nltk/parse/malt.py", line 122, in tagged_parse return DependencyGraph.load(output_file) File "/usr/local/lib/python2.7/dist-packages/nltk-2.0b5-py2.7.egg/nltk/parse/dependencygraph.py", line 121, in load return DependencyGraph(open(file).read()) IOError: [Errno 2] No such file or directory: '/tmp/malt_output.conll' Please help me to parse that sentence using this malt parser. Answer: # Edited Note that is answer is no longer working because of the updated version of the MaltParser API in NLTK since August 2015. This answer is kept for legacy sake. Please see this answers to get MaltParser working with NLTK: * [Step by step to getting malt parser in NLTK to work?](http://stackoverflow.com/questions/13207394/step-by-step-to-getting-malt-parser-in-nltk-to-work) **Disclaimer** : This is not an eternal solutions. The answer in the above link (posted on Feb 2016) will work for now. But when MaltParser or NLTK API changes, it might also change the syntax to using MaltParser in NLTK. * * * A couple problems with your setup: * The input to `train_from_file` must be a file in CoNLL format, not a pre-trained model. For an `mco` file, you pass it to the `MaltParser` constructor using the `mco` and `working_directory` parameters. * The default java heap allocation is not large enough to load that particular `mco` file, so you'll have to tell java to use more heap space with the `-Xmx` parameter. Unfortunately this wasn't possible with the existing code so I just checked in a change to allow an additional constructor parameters for java args. See [here](https://github.com/nltk/nltk/commit/f63cdccca48c39141f18f79a2cd182f3964eaa93). So here's what you need to do: First, get the latest NLTK revision: git clone https://github.com/nltk/nltk.git (NOTE: If you can't use the git version of NLTK, then you'll have to update the file `malt.py` manually or copy it from [here](https://github.com/nltk/nltk/blob/master/nltk/parse/malt.py) to have your own version.) Second, rename the jar file to `malt.jar`, which is what NLTK expects: cd /usr/lib/ ln -s maltparser-1.7.2.jar malt.jar Then add an environment variable pointing to malt parser: export MALTPARSERHOME="/Users/dhg/Downloads/maltparser-1.7.2" Finally, load and use malt parser in python: >>> import nltk >>> parser = nltk.parse.malt.MaltParser(working_dir="/home/rohith/malt-1.7.2", ... mco="engmalt.linear-1.7", ... additional_java_args=['-Xmx512m']) >>> txt = "This is a test sentence" >>> graph = parser.raw_parse(txt) >>> graph.tree().pprint() '(This (sentence is a test))'
installing theano package on windows Question: I am trying to install the theano package on my windows machine. I seem to have problem installing pip by typing : easy_install pip The python shell complains: SyntaxError: invalid syntax on pip. I am trying to install it on EPD and I have imported numpy before typing easy_install pip. I have been using the guidelines provided in : <http://deeplearning.net/software/theano/install.html> Answer: `easy_install` is a program that you should run from a system shell, not from within Python. It's usually located in `<your python folder>/Scripts/`, though I've not verified that this is true for the Enthought distribution.
HTTP-browsing library with active feedback Question: I have a webpage with a Flash object on it. I want to be able to click multiple different buttons within in. Regarding this method I was wondering if there is any library (preferable Python/Perl/JAVA) that can actually stream a page-open session, emulate a resolution and perform (x,y) clicks. For example (Python-like): I Load the SomeUrlLib: import SomeUrlLib browser = new SomeUrlLib() browser.setUrl('http://www.someaddress.com/subpage/') browser.setResolution(1280, 800) browser.startBrowsing('SessionName') # Bind a session name to this browsing session locX = 40 locY = 80 browser.click(locX, locY, 'SessionName') screen = browser.takeScreenshot('SessionName') I'm thinking this is nearly impossible, as I can't imagine any library out there would be able to have Flash-engine build-in. "If" this is possible in some weird way I would like to try to use the Sikuli API (screen recognition) to maybe react on screenshot feedback to click on certain coordinates, yet I guess dynamically changing pages are still an issue due to the latency the script would have towards what happens live in the page. Answer: It seems that there is extension for Selenium that enables flash. Selenium <http://seleniumhq.org/> Selenium python <http://pypi.python.org/pypi/selenium/> Selenium extension for flash | works in python too <http://code.google.com/p/flash-selenium/>
Sorting a networkx graph object Python Question: I want to sort a graph object that I have read through networkx library in Python, in the increasing order of edgeweight. It seems that the `sort` command of python won't apply to graph objects. I am sure there is a easy way to sort this object, but I am not sure how. Any help will be appreciated. For example, my first three edges are 1 3 5250 1 4 74 1 5 3659 After sorting I would hope that their order is changed to 1 4 74 1 5 3659 1 3 5250 Here is my code so far import networkx as nx g=nx.read_weighted_edgelist(fname,nodetype=int) I am trying to sort the object `g`. Answer: import networkx as nx edgelist = [ (1, 3, {'weight':5250}), (1, 4, {'weight': 74}), (1, 5, {'weight': 3659})] G = nx.Graph(edgelist) for a, b, data in sorted(G.edges(data=True), key=lambda (a, b, data): data['weight']): print('{a} {b} {w}'.format(a=a, b=b, w=data['weight'])) yields 1 4 74 1 5 3659 1 3 5250
Making a variable cross module in Python - Within a class and function Question: I'm trying to use a variable in other python modules, like this: In `a.py`: class Names: def userNames(self): self.name = 'Richard' In `z.py`: import a d = a.Names.name print d However this doesn't recognise the variable `name` and the following error is received: AttributeError: type object 'Names' has no attribute 'name' Thanks Answer: > "I've checked again and it's because I'm importing from is a Tornado > Framework and the variable is within a class." Accordingly, your problem is not the one shown in your question. If you actually want to access the variable of a class (and likely, you don't), then do this: from othermodule import ClassName print ClassName.var_i_want You probably want to access the variable as held inside an instance: from othermodule import ClassName, some_func classnameinstance = some_func(blah) print classnameinstance.var_i_want **Update** Now that you have completely changed your question, here is the answer to your new question: IN this code: class Names: def userNames(self): name = 'Richard' `name` is not a variable accessible outside of the activation of the method `userNames`. This is known as a local variable. You would create an instance variable by changing the code to: def userNames(self): self.name = 'Richard' Then, if you have an instance in a variable called `classnameinstance` you can do: print classnameinstance.name This will only work if the variable has been already created on the instance, as by calling `userNames`. You don't need to import the class itself if there is some other way to receive instances of the class.
How to convert a number in Python to 8 binary bytes (64-bit long)? Question: How do I convert a number in Python to 8 binary bytes (64-bit long)? I have a blueprint of a network message, part of which is a number represented with eight bytes. Answer: Use [struct.pack](http://docs.python.org/2/library/struct.html#format- strings): >>> import struct >>> struct.pack('!Q', 123) '\x00\x00\x00\x00\x00\x00\x00{' The first argument is a [format string](http://docs.python.org/2/library/struct.html#format-strings) which controls the encoding. `!` means network byte order and `Q` is for 8-byte unsigned integers.
Making the leap from PhP to Python Question: I am a fairly comfortable PHP programmer, and have very little Python experience. I am trying to help a buddy with his project, the code is easy enough to write in Php, I have most of it ported over, but need a bit of help completing the translation if possible. The target is to: * Generate a list of basic objects with uid's * Randomly select a few Items to create a second list keyed to the uid containing new properties. * Test for intersections between the two lists to alter response accordingly. The following is a working example of what I am trying to code in Python <?php srand(3234); class Object{ // Basic item description public $x =null; public $y =null; public $name =null; public $uid =null; } class Trace{ // Used to update status or move position # public $x =null; # public $y =null; # public $floor =null; public $display =null; // Currently all we care about is controlling display } ########################################################## $objects = array(); $dirtyItems = array(); #CREATION OF ITEMS######################################## for($i = 0; $i < 10; $i++){ $objects[] = new Object(); $objects[$i]->uid = rand(); $objects[$i]->x = rand(1,30); $objects[$i]->y = rand(1,30); $objects[$i]->name = "Item$i"; } ########################################################## #RANDOM ITEM REMOVAL###################################### foreach( $objects as $item ) if( rand(1,10) <= 2 ){ // Simulate full code with 20% chance to remove an item. $derp = new Trace(); $derp->display = false; $dirtyItems[$item->uid] = $derp; //# <- THIS IS WHERE I NEED THE PYTHON HELP } ########################################################## display(); function display(){ global $objects, $dirtyItems; foreach( $objects as $key => $value ){ // Iterate object list if( @is_null($dirtyItems[$value->uid]) ) // Print description echo "<br />$value->name is at ($value->x, $value->y) "; else // or Skip if on second list. echo "<br />Player took item $value->uid"; } } ?> So, really I have most of it sorted I am just having trouble with Python's version of an Associative array, to have a list whose keys match the Unique number of Items in the main list. The output from the above code should look similar to: Player took item 27955 Player took item 20718 Player took item 10277 Item3 is at (8, 4) Item4 is at (11, 13) Item5 is at (3, 15) Item6 is at (20, 5) Item7 is at (24, 25) Item8 is at (12, 13) Player took item 30326 My Python skills are still course, but this is roughly the same code block as above. I've been looking at and trying to use list functions .insert( ) or .setitem( ) but it is not quite working as expected. This is my current Python code, not yet fully functional import random import math # Begin New Globals dirtyItems = {} # This is where we store the object info class SimpleClass: # This is what we store the object info as pass # End New Globals # Existing deffinitions objects = [] class Object: def __init__(self,x,y,name,uid): self.x = x # X and Y positioning self.y = y # self.name = name #What will display on a 'look' command. self.uid = uid def do_items(): global dirtyItems, objects for count in xrange(10): X=random.randrange(1,20) Y=random.randrange(1,20) UID = int(math.floor(random.random()*10000)) item = Object(X,Y,'Item'+str(count),UID) try: #This is the new part, we defined the item, now we see if the player has moved it if dirtyItems[UID]: print 'Player took ', UID except KeyError: objects.append(item) # Back to existing code after this pass # Any error generated attempting to access means that the item is untouched by the player. # place_items( ) random.seed(1234) do_items() for key in objects: print "%s at %s %s." % (key.name, key.x, key.y) if random.randint(1, 10) <= 1: print key.name, 'should be missing below' x = SimpleClass() x.display = False dirtyItems[key.uid]=x print ' ' objects = [] random.seed(1234) do_items() for key in objects: print "%s at %s %s." % (key.name, key.x, key.y) print 'Done.' So, sorry for the long post, but I wanted to be through and provide both sets of full code. The PhP works perfectly, and the Python is close. If anyone can point me in the correct direction it would be a huge help. **dirtyItems.insert(key.uid,x)** is what i tried to use to make a list work as an Assoc array _Edit: minor correction._ Answer: You're declaring `dirtyItems` as an array instead of a dictionary. In python they're distinct types. Do `dirtyItems = {}` instead.
Filter broken referer Django emails when switching servers Question: We often change IP addresses on AWS when switching EC2 servers (yes, we use Elastic IPs when applicable). Sometimes we get IP addresses that used to host other applications (which is fine, of course). When end users click on stale links they get to our servers (which is ok). But these HTTP GET requests have a "referer" header, thus the regular 404 error generates an automated Django email to our developers! I can recreate the error emails easily using the following Python code: import urllib2 req = urllib2.Request('http://my_website.com/some/url/we/dont/have') req.add_header('Referer', 'http://whatever.i.want') request = urllib2.urlopen(req) When the Referer header is commented out Django does not send emails. We still want the emails to be sent when there are real broken links in OUR website, so I do not want to set `SEND_BROKEN_LINK_EMAILS` to False. I cannot filter using `IGNORABLE_404_URLS` because a. the logic is reversed and b. the regular expression only scans the path and not the hostname. Help? Answer: I'd probably knock up some [middleware](https://docs.djangoproject.com/en/dev/topics/http/middleware/?from=olddocs#process- exception) that catches the `Http404` exception, examines the referer header, and either raises a separate exception (probably will still be mailed though), or does a simple redirect to your front page. Even better, create a custom page describing why the user ended up where they are, and just redirect to that.
Cheap mapping of string to small fixed-length string Question: Just for _debugging_ purposes I would like to map a big string (a session_id, which is difficult to visualize) to a, let's say, 6 character "hash". This hash does not need to be secure in any way, just cheap to compute, and of fixed and reduced length (md5 is too long). The input string can have any length. How would you implement this "cheap_hash" in python so that it is not expensive to compute? It should generate something like this: def compute_cheap_hash(txt, length=6): # do some computation return cheap_hash print compute_cheap_hash("SDFSGSADSADFSasdfgsadfSDASAFSAGAsaDSFSA2345435adfdasgsaed") aBxr5u Answer: def cheaphash(string,length=6): if length<len(hashlib.sha256(string).hexdigest()): return hashlib.sha256(string).hexdigest()[:length] else: raise Exception("Length too long. Length of {y} when hash length is {x}.".format(x=str(len(hashlib.sha256(string).hexdigest())),y=length)) This should do what you need it to do, it simply uses the `hashlib` module, so make sure to import it before using this function.
BYTE to python C-Type structure Conversion Issue Question: I am facing a little problem on deserializing some bytes that have been received from the POSIX Queue. We are trying to develop a module where a Python application will post a POSIX queue data to a C application and C will re-post data to Python Queue.. All data is Ctype Structure based. Structure defintion: **msgStruct.py** MAX_MSG_SIZE = 5120 class MsgStruct(ctypes.Structure): _fields_ = [ ("msgType", ctypes.c_int), ("msgSize",ctypes.c_int), ("setState",ctypes.c_int), ("msgBuf",ctypes.c_char * MAX_MSG_SIZE) ] **conversions.py** class conversions(): def serialize(ctypesObj): """ FAQ: How do I copy bytes to Python from a ctypes.Structure? """ return buffer(ctypesObj)[:] def deserialize(ctypesObj, inputBytes): """ FAQ: How do I copy bytes to a ctypes.Structure from Python? """ fit = min(len(inputBytes), ctypes.sizeof(ctypesObj)) ctypes.memmove(ctypes.addressof(ctypesObj), inputBytes, fit) return ctypesObj **test.py** from mapStruct import * from conversions import conversions wrapper=conversions() data="\x01\x00\x00\x00\x70\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x1e\x00\x00\x00\x25\x42\x35\x32\x33\x39\x35\x31\x32\x35\x32\x34\x38\x39\x35\x30\x30\x36\x5e\x56\x45\x4e\x4b\x41\x54\x20\x52\x41\x47\x41\x56\x41\x4e\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x5e\x31\x36\x30\x34\x31\x30\x31\x31\x36\x35\x35\x36\x30\x30\x31\x34\x31\x30\x30\x30\x30\x30\x30\x3f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x3b\x35\x32\x33\x39\x35\x31\x32\x35\x32\x34\x38\x39\x35\x30\x30\x36\x3d\x31\x36\x30\x34\x31\x30\x31\x31\x34\x31\x30\x3f\x00\x00...\x00" """ Data is the Queue data that is recieved by python """ baseStruct=MsgStruct() rxData=wrapper.deserialize(baseStruct,data) print rxData.setState # Prints as expected print rxData.msgType # Prints as expected print rxData.msgSize print rxData.msgBuf.encode('hex') # here is probles i dont C any data in this buffer Please guide me on solving this issue. I am very much surprised that the buffer(rxData.msgSize) is always empty and would like to know why. Answer: `ctypes` is trying to be helpful with `c_char` buffers by converting it into a Python string. The conversion stops at the first null byte. Observe what happens when I change the first couple bytes of data in your data buffer: 0 1 368 b'\x01\x02' Change the type of `msgBuf` to `c_ubyte` instead so `ctypes` won't try to be "helpful" and then look at the data character-by-character with: >>> print repr(''.join(chr(x) for x in rxData.msgBuf)) '\x00\x00\x00\x00\x02\x00\x00\x00\x1e\x00\x00\x00%B5239512524 ... But there is no reason to use `ctypes` at all: import struct data=b"\x01\x00\x00\x00\x70\x01\x00\x00\x00\x00\x00\x00\x01\x02\x00\x00\x02\x00\x00\x00\x1e\x00\x00\x00\x25\x42\x35\x32\x33\x39\x35\x31\x32\x35\x32\x34\x38\x39\x35\x30\x30\x36\x5e\x56\x45\x4e\x4b\x41\x54\x20\x52\x41\x47\x41\x56\x41\x4e\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x5e\x31\x36\x30\x34\x31\x30\x31\x31\x36\x35\x35\x36\x30\x30\x31\x34\x31\x30\x30\x30\x30\x30\x30\x3f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x3b\x35\x32\x33\x39\x35\x31\x32\x35\x32\x34\x38\x39\x35\x30\x30\x36\x3d\x31\x36\x30\x34\x31\x30\x31\x31\x34\x31\x30\x3f\x00\x00...\x00" msg_offset = struct.calcsize('iii') print struct.unpack_from('iii',data) print repr(data[msg_offset:]) Output: (1, 368, 0) '\x01\x02\x00\x00\x02\x00\x00\x00\x1e\x00\x00\x00%B5239512524895006^VENKAT RAGAVAN ^16041011655600141000000?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00;5239512524895006=16041011410?\x00\x00...\x00'
Checking for some exact lines in each file in directory and subdirectories Question: I am trying to do the following and running into errors,what is going wrong? 1.Open each file in the directory and subdirectories based on the argument 2.Check if each file has the copyright info exactly the 3 lines Copyright (c) 2012 Company, Inc. All Rights Reserved. Company Confidential and Proprietary. The code: import os import sys userstring="Copyright (c) 2012 Company, Inc.\nAll Rights Reserved.\nCompany Confidential and Proprietary." print len(sys.argv) print sys.argv[1] if len(sys.argv) < 2: sys.exit('Usage: python.py <build directory>') for r,d,f in os.walk(sys.argv[1]): for files in f: with open(os.path.join(r, files), "r") as file: if ''.join(file.readlines()[:3]).strip() != userstring: print files Answer: Maybe by changing these lines: file = open(files, "r") if userstring not in line: #check if each file contains the lines print file To these: with open(os.path.join(r, files), "r") as file: if ''.join(file.readlines()[:3]).strip() != userstring: print files You achieve your goal. But when you're working with files, you should be aware about bad files bad formatting and exception handling and etc.
Issues with script on 64bit Ubuntu Question: I have used one script, `https://github.com/reddit/reddit/blob/master/install- reddit.sh` on several machines and every time it worked perfectly. Now, one one server which has Ubuntu 64bit, I encounter issues with one part of the script. ############################################################################### # Configure PostgreSQL ############################################################################### SQL="SELECT COUNT(1) FROM pg_catalog.pg_database WHERE datname = 'reddit';" IS_DATABASE_CREATED=$(sudo -u postgres psql -t -c "$SQL") if [ $IS_DATABASE_CREATED -ne 1 ]; then cat <<PGSCRIPT | sudo -u postgres psql CREATE DATABASE reddit WITH ENCODING = 'utf8' TEMPLATE template0; CREATE USER reddit WITH PASSWORD 'password'; PGSCRIPT fi sudo -u postgres psql reddit < $REDDIT_HOME/reddit/sql/functions.sql This is basically breaking the whole install process. I have tried running the lines manually from the script, like `sudo -u postgres psql` but I get no output at all. It seems that the database creation is not complete, because if I follow the guide for manually setting up POSTGRESQL, the command `sudo -u postgres initdb -D /usr/local/pgsql/data` fails with this output: sudo: initdb: command not found I also tried adding things to the path, `export PATH=$PATH:/usr/lib/postgresql/bin` but without help too, initdb wont start. Postgresql is installed, so I don't really know what is causing this. Output of `/etc/init.d/postgresql status` is `Running clusters: 9.1/main` so the service is running. I even tried installing ia32-libs and libc6-i386 but that didn't do much difference either. UPDATE: After dealing with that issue, as described in the comments, I have encountered another one. I will put this here too as I think it's also closely related to this. I get the following error then: + sudo -u reddit make pyx [+] including definitions from Makefile.py python setup.py build_ext --inplace /home/reddit/reddit/r2/ez_setup.py:101: UserWarning: Module ez_setup was already imported from /home/reddit/reddit/r2/ez_setup.pyc, but /usr/lib/pymodules/python2.7 is being added to sys.path import pkg_resources running build_ext skipping './r2/models/_builder.c' Cython extension (up-to-date) building 'r2.models._builder' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c ./r2/models/_builder.c -o build/temp.linux-x86_64-2.7/./r2/models/_builder.o unable to execute gcc: Permission denied error: command 'gcc' failed with exit status 1 So, this gcc thing is now causing issues. This lines are triggering this: cd $REDDIT_HOME/reddit/r2 sudo -u $REDDIT_OWNER make pyx # generate the .c files from .pyx $REDDIT_OWNER is reddit, so it runs as that user, and that ends up in those errors. Can anyone suggest a potential solution for this too? make: _*_ [build/pyx-buildstamp] Error 1 Thanks for your help! Answer: You're probably running into a problem where the PATH get reset by sudo. See [here](http://stackoverflow.com/questions/257616/sudo-changes-path-why)
How do I allow opening of files that have Unicode characters in their filenames? Question: I have this Python script here that opens a random video file in a directory when run: import glob,random,os files = glob.glob("*.mkv") files.extend(glob.glob("*.mp4")) files.extend(glob.glob("*.tp")) files.extend(glob.glob("*.avi")) files.extend(glob.glob("*.ts")) files.extend(glob.glob("*.flv")) files.extend(glob.glob("*.mov")) file = random.choice(files) print "Opening file %s..." % file cmd = "rundll32 url.dll,FileProtocolHandler \"" + file + "\"" os.system(cmd) Source: An answer in my Super User post, '[How do I open a random file in a folder, and set that only files with the specified filename extension(s) should be opened?](http://superuser.com/questions/512867/how-do-i-open-a- random-file-in-a-folder-and-set-that-only-files-with-the-specif)' This is called by a BAT file, with this as its script: C:\Python27\python.exe "C:\Programs\Scripts\open-random-video.py" cd I put this BAT file in the directory I want to open random videos of. In most cases it works fine. However, I can't make it open files with Unicode characters (like Japanese or Korean characters in my case) in their filenames. This is the error message when the BAT file and Python script is run on a directory and opens a file with Unicode characters in its filename: `C:\TestDir>openrandomvideo.BAT` `C:\TestDir>∩╗┐C:\Python27\python.exe "C:\Programs\Scripts\open-random- video.py" cd` `The filename, directory name, or volume label syntax is incorrect.` Note that the filename of the .FLV video file in that log is changed from its original filename (소시.flv) to '∩╗┐' in the command line log. EDIT: I learned that the above command line error message is due to [saving the BAT file as 'UTF-8 with BOM'](http://stackoverflow.com/a/14033531/1626811). Saving it as 'ANSI or UTF-16' shows the following message instead, but still does not open the file: C:\TestDir>openrandomvideo.BAT C:\TestDir>C:\Python27\python.exe "C:\Programs\Scripts\open-random-video.py" cd Opening file ??.flv... Now, the filename of the .FLV video file in that log is changed from its original filename (소시.flv) to '??.flv.' in the command line log. I'm using Python 2.7 on Windows 7, 64-bit. **How do I allow opening of files that have Unicode characters in their filenames?** Answer: Just use Unicode literals e.g., `u".mp4"` everywhere. IO functions in Python will return Unicode filenames back if you give them Unicode input (internally they might use Unicode-aware Windows API): import os import random videodir = u"." # get videos from current directory extensions = tuple(u".mkv .mp4 .tp .avi .ts .flv .mov".split()) files = [file for file in os.listdir(videodir) if file.endswith(extensions)] if files: # at least one video file exists random_file = random.choice(files) os.startfile(os.path.join(videodir, random_file)) # start the video else: print('No %s files found in "%s"' % ("|".join(extensions), videodir,)) If you want to emulate how your web browser would open video files then you could use `webbrowser.open()` instead of `os.startfile()` though the former might use the latter internally on Windows anyway.