text
stringlengths
226
34.5k
Network Pinging with Python Question: Is there a way i can ping requests of a particular website for a particular no. of times using Python and also is there a way through which i can decide the no . of packets of data to be send in each request ? Answer: You can use the os module for this. 5 is the count www.examplesite.com is the site import os os.system("ping -c 5 www.examplesite.com") Hope it helped
Guess the number game optimization (user creates number, computer guesses) Question: I am very new to programming so I decided to start with Python about 4 or 5 days ago. I came across a challenge that asked for me to create a "Guess the number" game. After completion, the "hard challenge" was to create a guess the number game that the user creates the number and the computer (AI) guesses. So far I have come up with this and it works, but it could be better and I'll explain. from random import randint print ("In this program you will enter a number between 1 - 100." "\nAfter the computer will try to guess your number!") number = 0 while number < 1 or number >100: number = int(input("\n\nEnter a number for the computer to guess: ")) if number > 100: print ("Number must be lower than or equal to 100!") if number < 1: print ("Number must be greater than or equal to 1!") guess = randint(1, 100) print ("The computer takes a guess...", guess) while guess != number: if guess > number: guess -= 1 guess = randint(1, guess) else: guess += 1 guess = randint(guess, 100) print ("The computer takes a guess...", guess) print ("The computer guessed", guess, "and it was correct!") This is what happened on my last run: Enter a number for the computer to guess: 78 The computer takes a guess... 74 The computer takes a guess... 89 The computer takes a guess... 55 The computer takes a guess... 78 The computer guessed 78 and it was correct! Notice that it works, however when the computer guessed 74, it then guessed a higher number to 89. The number is too high so the computer guesses a lower number, however the number chosen was 55. Is there a way that I can have the computer guess a number that is lower than 89, but higher than 74? Would this require additional variables or more complex if, elif, else statements? **Thank you Ryan Haining** I used the code from your reply and altered it slightly so the guess is always random. If you see this, let me know if this is the best way to do so. from random import randint def computer_guess(num): low = 1 high = 100 # This will make the computer's first guess random guess = randint(1,100) while guess != num: print("The computer takes a guess...", guess) if guess > num: high = guess elif guess < num: low = guess + 1 # having the next guess be after the elif statement # will allow for the random guess to take place # instead of the first guess being 50 each time # or whatever the outcome of your low+high division guess = (low+high)//2 print("The computer guessed", guess, "and it was correct!") def main(): num = int(input("Enter a number: ")) if num < 1 or num > 100: print("Must be in range [1, 100]") else: computer_guess(num) if __name__ == '__main__': main() Answer: what you are looking for is the classic [binary search algorithm](http://en.wikipedia.org/wiki/Binary_search_algorithm) def computer_guess(num): low = 1 high = 100 guess = 50 while guess != num: guess = (low+high)//2 print("The computer takes a guess...", guess) if guess > num: high = guess elif guess < num: low = guess + 1 print("The computer guessed", guess, "and it was correct!") def main(): num = int(input("Enter a number: ")) if num < 1 or num > 100: print("Must be in range [1, 100]") else: computer_guess(num) if __name__ == '__main__': main() The algorithm works by selecting a low and high limit to start with (in your case low=1 and high=100). It then checks the midpoint between them. If the midpoint is less than number, the midpoint becomes the new lower bound. If the midpoint is higher, it becomes the new upper bound. After doing this a new midpoint is generated between the upper and lower bound. To illustrate an example let's say you're looking for 82. Here's a sample run Enter a number: 82 The computer takes a guess... 50 The computer takes a guess... 75 The computer takes a guess... 88 The computer takes a guess... 82 The computer guessed 82 and it was correct! So what's happening here in each step? 1. `low = 1`, `high = 100` => `guess = 50` 50 < 82 so `low = 51` 2. `low = 51`, `high = 100` => `guess = 75` 75 < 82 so `low = 76` 3. `low = 76`, `high = 100` => `guess = 88` 88 > 82 so `high = 88` 4. `low = 76`, `high = 88` => `guess = 82` 82 == 82 and we're done. Note that the time complexity of this is `O(lg(N))`
How can a print elements in a list randomly in python? Question: I've got a list which I want to print in random order. Here is the code I've written so far: import random words=["python","java","constant","immutable"] for i in words: print(i, end=" ") input("") #stops window closing I've tried a variety of things to print them out randomly, such as making a variable which selects only one of them randomly and then deleting the randomly. I would then repeat this step until they are all deleted and within another variable. Then I would put the variables in a list then print them out. This kept on generating errors though. Is there another way this can be done? Answer: Use [`random.shuffle()`](http://docs.python.org/3/library/random.html#random.shuffle) to shuffle a list, in-place: import random words = ["python", "java", "constant", "immutable"] random.shuffle(words) print(*words) input('') Demo: >>> import random >>> words = ["python", "java", "constant", "immutable"] >>> random.shuffle(words) >>> words ['python', 'java', 'constant', 'immutable'] If you wanted to preserve `words` (maintain the order), you can use `sorted()` with a random key to return a new randomized list: words = ["python", "java", "constant", "immutable"] print(*sorted(words, key=lambda k: random.random())) This leaves `words` unaltered: >>> words = ["python", "java", "constant", "immutable"] >>> sorted(words, key=lambda k: random.random()) ['immutable', 'java', 'constant', 'python'] >>> words ['python', 'java', 'constant', 'immutable']
Continuous loop using threading Question: I am somewhat new to python. I have been trying to find the answer to this coding question for some time. I have a function set up to run on a threading timer. This allows it to execute every second while my other code is running. I would like this function to simply execute continuously, that is every time it is done executing it starts over, rather than on a timer. The reason for this is that due to a changing delay in a stepper motor the function takes different amounts of time run. Answer: Is this what you're looking for? from threading import Thread def f(): print('hello') while True: t = Thread(target=f) t.start() t.join() Or maybe this, which shows the concurrent paths of execution (for production, remove `sleep()` calls, of course): from threading import Thread from time import sleep def g(): print('hello') sleep(1) def f(): while True: g() Thread(target=f).start() sleep(1) print('other code here')
python numpy and memory efficiency (pass by reference vs. value) Question: I've recently been using python more and more in place of c/c++ because of it cuts my coding time by a factor of a few. At the same time, when I'm processing large amounts of data, the speed at which my python programs run starts to become a lot slower than in c. I'm wondering if this is due to me using large objects/arrays inefficiently. **Is there any comprehensive guide just to how memory is handled by numpy/python? When things are passed by reference and when by value, when things are copied and when not, what types are mutable and which are not.** Answer: Objects in python (and most mainstream languages) are passed as reference. If we take numpy, for example, "new" arrays created by indexing existing ones are only views of the original. For example: import numpy as np >>> vec_1 = np.array([range(10)]) >>> vec_1 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> vec_2 = vec_1[3:] # let vec_2 be vec_1 from the third element untill the end >>> vec_2 array([3, 4, 5, 6, 7, 8, 9]) >>> vec_2[3] = 10000 array([3, 4, 5, 10000, 7, 8, 9]) >>> vec_1 array([0, 1, 2, 3, 4, 5, 10000, 7, 8, 9]) Numpy have a handy method to help with your questions, called may_share_memory(obj1, obj2). So: >>> np.may_share_memory(vec_1, vec_2) True Just be carefull, because it`s possible for the method to return false positives (Although i never saw one). At SciPy 2013 there was a tutorial on numpy (<http://conference.scipy.org/scipy2013/tutorial_detail.php?id=100>). At the end the guy talks a little about how numpy handles memory. Watch it. As a rule of thumb, objects are almost never passed as value by default. Even the ones encapsulated on another object. Another example, where a list makes a tour: Class SomeClass(): def __init__(a_list): self.inside_list = a_list def get_list(self): return self.inside_list >>> original_list = range(5) >>> original_list [0,1,2,3,4] >>> my_object = SomeClass(original_list) >>> output_list = my_object.get_list() >>> output_list [0,1,2,3,4] >>> output_list[4] = 10000 >>> output_list [0,1,2,3,10000] >>> my_object.original_list [0,1,2,3,10000] >>> original_list [0,1,2,3,10000] Creepy, huh? Using the assignment symbol ("="), or returning one in the end of a function you will always create a pointer to the object, or a portion of it. **Objects are only duplicated when you explicitly do so** , using a copy method like some_dict.copy, or array[:]. For example: >>> original_list = range(5) >>> original_list [0,1,2,3,4] >>> my_object = SomeClass(original_list[:]) >>> output_list = my_object.get_list() >>> output_list [0,1,2,3,4] >>> output_list[4] = 10000 >>> output_list [0,1,2,3,10000] >>> my_object.original_list [0,1,2,3,10000] >>> original_list [0,1,2,3,4] Got it?
Python: Adding an entry? Question: I'm trying to write a program that asks a user to enter a product name, the price, and quantity. From there, all the info will be added to a table (dictionary?) Also, an ID number must be assigned to all new items created. I'm confused about the ID number segment. items = {} product = str(input("Enter the name of a product: ")) price = int(input("Enter a price: ")) quantity = int(input("Enter a quantity: ")) #Assign unique ID number. I'm trying to get the result below as an example: ID#70271, shoes. 7 available, at $77.00 Answer: You could use [uuid4](http://docs.python.org/2/library/uuid.html#uuid.uuid4) to create the unique id >>> from uuid import uuid4 >>> uuid4().clock_seq 7972L >>> uuid4().clock_seq 11807L >>> uuid4().clock_seq 15487L
ASCIIMathMl in ipython notebook Question: Since ipython notebook renders math using the mathjax library. Mathjax officially supports the asciimath syntax. But I'm unable to get it rendered correctly in ipython notebook from IPython.display import Math Math(r'x^2 or a_(m n) or a_{m n} or (x+1)/y or sqrtx') the syntax inside the quotes is [asciimath](http://www1.chapman.edu/~jipsen/mathml/asciimathsyntax.html) syntax. IPython notebook 1.0 dev cannot render it correctly. Is there a way to enable this support. Answer: I have not tried it but this link is supposed to show how to enable asciimath in an [ipython notebook](https://github.com/ipython/ipython/issues/4052). One of the developers explains why they prefer to use LaTeX.
Python - Django - activate() returns None Question: Okay, so I'm trying to create a log in with Django. from views.py: from django.shortcuts import * from forms import UserRegistrationForm from django.contrib.auth import authenticate, login from django.core.mail import send_mail from django.conf import settings import pprint import utils import models from django.http import HttpResponse import views from django.conf.urls import patterns, url def login_user(request): state = "Please log in below..." username = password = '' if request.POST: username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: if not user.is_verified: state = "Please check your e-mail to verify your account." elif user.is_active: login(request, user) state = "You're successfully logged in!" else: state = "Your account is not active, please contact the site admin." else: state = "Your username and/or password were incorrect." return render_to_response('myapp/dashboard.html', {'state': state}, RequestContext(request)) else: return render_to_response('myapp/login.html', RequestContext(request)) My login template (login.html): <h3>Login</h3><hr /> <form action="/login/" method="post"> {% csrf_token %} {% if next %} <input type="hidden" name="next" value="{{ next }}" /> {% endif %} username: <input type="text" name="username" value="{{ username }}" /><br /> password: <input type="password" name="password" value="" /><br /> <input class="btn" type="submit" value="Log In" /> </form> I'm using a basic SQLite3 to get everything figured out. python manage.py syncdb runs with no problems from settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'tempDB' } } When I log into my admin site I see the user: > username: nick password: the hashed version of nick When I insert a break (using PBD) I was able to see that the app goes through the login_user view. > ...myapp/myapp/views.py(52)login_user() -> state = "Please log in below..." (Pdb) n > ...myapp/myapp/views.py(53)login_user() -> username = password = '' (Pdb) print username *** NameError: name 'username' is not defined (Pdb) n > ...myapp/myapp/views.py(55)login_user() -> if request.POST: (Pdb) print username (Pdb) n > ...myapp/myapp/views.py(56)login_user() -> username = request.POST.get('username') (Pdb) print username (Pdb) n > ...myapp/myapp/views.py(57)login_user() -> password = request.POST.get('password') (Pdb) print username nick (Pdb) n > ...myapp/myapp/views.py(59)login_user() -> user = authenticate(username=username, password=password) (Pdb) print password nick (Pdb) n > ...myapp/myapp/views.py(61)login_user() -> if user is not None: (Pdb) print user None This shows that it gets the username 'nick' and the password 'nick' (the settings that I set the account up with) however the problem I run into is that authenticate is still returning None which means SOMETHING is not set up correctly / is not working. After that login_user view the 'state' prints "Your username and/or password were incorrect." as told to do in views.py I would greatly appreciate it if someone would be able to help me out! Answer: _(Replied on G+ as well)_ From your pdb session: (Pdb) print password nick If that's what happens, there's a problem there, don't you agree? Also, I'd do away with the initialization of the vars and do this instead: username = request.POST.get('username') password = request.POST.get('password') if username and password: # Your code request.POST.get will work anyway (POST is always initialized as a QueryDict) and the get() returns None if the key is not found, so you won't get any errors - and it might be easier for you to see what's going on.
python default argument syntax error Question: I just wrote a small text class in python for a game written using pygame and for some reason my default arguments aren't working. I tried looking at the python documentation to see if that might give me an idea what I did wrong, but I didn't fully get the language in the documentation. No one else seems to be having this issue. Here's the code for the text class: class Text: def __init__(self,screen,x_location='center',y_location='center',writeable,color,size=12): self.font = pygame.font.Font("Milleni Gem.ttf", size) self.text = self.font.render(writeable,True,color) self.textRect = self.text.get_rect() if x_location == "center": self.textRect.centerx = screen.get_rect().centerx else: self.textRect.x = x_location if y_location == "center": self.textRect.centery = screen.get_rect().centery else: self.textRect.y = y_location self.update() def update(self): screen.blit(self.text,self.textRect) and here's the code to call it: from gui import * Text(screen,75,75,currentweapon.clip)#currentweapon.clip is an integer The error I get is this: SyntaxError: non-default argument follows default argument and points to the `def __init__()` line in the code. What does this error mean and what am I doing wrong here? Answer: def __init__(self,screen,x_location='center',y_location='center',writeable,color,size=12): You have defined non-default arguments after default arguments, this is not allowed. You should use: def __init__(self,screen,writeable,color,x_location='center',y_location='center',size=12):
How to write to a new line every time in python? Question: I'm just trying to append new tweets that come in to a new line in a file.... So far nothing i'm trying works on OS X Python. class CustomStreamListener(tweepy.StreamListener): def on_status(self, status): print status.text with open("myNewFile", "a") as file: file.write('\n') file.write("\n" + status.text + "\n") file.write('\n') Any ideas? Answer: You have an issue with indentation: with open("myNewFile", "a") as file: file.write('\n') file.write("\n" + status.text + "\n") file.write('\n') If you want to be inside the `with` context, you should indent the following three lines to the right. Further, you can use `format()` to prepare the string you want to write, for efficiency and readibility: import os with open("myNewFile", "a") as file: file.write('{0}{0} {1} {0}{0}'.format(os.linesep, status.text) #file.write('\n') #file.write("\n" + status.text + "\n") #file.write('\n') Note the `os.linesep` to insert an OS independent new line :). You can also write two `linesep` by repeating them twice (multiply the string by 2): file.write('{0} {1} {0}'.format(os.linesep * 2, status.text) Which is cleaner.
Python Adding Headers to urlparse Question: There doesn't appear to be a way to add headers to the urlparse command. This essentially causes Python to use its default user agent, which is blocked by several web pages. What I am trying to do is essentially do the equivalent of this: req = Request(INPUT_URL,headers={'User-Agent':'Browser Agent'}) But using urlparse: parsed = list(urlparse(INPUT_URL)) So how can I modify this urlparse in order for it to take headers, or be usable with my Request that I created? Any help is appreciated, thanks. Also, for anyone wondering the exact error I am getting: urllib.error.HTTPError: HTTP Error 403: Forbidden At this: urlretrieve(urlunparse(parsed),outpath) Answer: Headers are part of a request, of which the URL is one part. Python creates a request for you when you pass in just a URL to `urllib.request` functions. Create a [`Request` object](http://docs.python.org/3/library/urllib.request.html#urllib.request.Request), add the headers to that object and use that instead of a string URL: request = Request(urlunparse(parsed), headers={'User-Agent': 'My own agent string'}) However, `urlretrieve()` is marked as 'legacy API' in the code and doesn't support using a `Request` object. Removing a few lines supporting 'file://' urls is easy enough: import contextlib import tempfile from urllib.error import ContentTooShortError from urllib.request import urlopen _url_tempfiles = [] def urlretrieve(url, filename=None, reporthook=None, data=None): with contextlib.closing(urlopen(url, data)) as fp: headers = fp.info() # Handle temporary file setup. if filename: tfp = open(filename, 'wb') else: tfp = tempfile.NamedTemporaryFile(delete=False) filename = tfp.name _url_tempfiles.append(filename) with tfp: result = filename, headers bs = 1024*8 size = -1 read = 0 blocknum = 0 if "content-length" in headers: size = int(headers["Content-Length"]) if reporthook: reporthook(blocknum, bs, size) while True: block = fp.read(bs) if not block: break read += len(block) tfp.write(block) blocknum += 1 if reporthook: reporthook(blocknum, bs, size) if size >= 0 and read < size: raise ContentTooShortError( "retrieval incomplete: got only %i out of %i bytes" % (read, size), result) return result
Show native import attempts in python3 Question: I wrote a Python 3 extension module in C but cannot seem to get Python to import it. Is there any way to let Python print out which shared libraries (.so on Linux) it tries to load and why it fails? Sadly all the docs I read don't really help since none describes the native import procedure in a concise way. What I tried is: ctypes.CDLL("libmydep1.so") ctypes.CDLL("libmydep2.so") try: import my_main print("Load python") except: ctypes.CDLL("libmylib.so") print("Load shared object") Which always prints `Load shared object`. `libmylib.so` contains the python entry point but loading it as Python 3 extension does not seem to work, although loading as a shared library does. **EDIT:** Python does not honor linux conventions. So for a lib you do not name it `libmylib.so` but `mylib.so`. Even worse, it only loads `my_main`, when the so is named `my_main.so`. So annoying. Answer: Try to look at `/proc/<pid>/maps` directory. Or try to use `lsof -p <PID>` command in shell. Source of answer is [this forum](http://www.unix.com/programming/34498-how- view-loaded-shared-libraries-running-processes-linux.html). lsof [man page](http://linux.die.net/man/8/lsof). See also [this answer](http://stackoverflow.com/questions/5103443/how-to-check-what-shared- library-is-loaded-at-run-time).
crontab with sudo python script Question: Alright, I've found something. Not sure how to tackle it. I've seen that this is a common error that comes up in google. The error seems to have something to do with the environment variables or something. Not sure how to handle this: This is the code and it's the part where subprocess is called that leads to the error: #!/usr/bin/python import subprocess import re import sys import time import datetime import gspread # =========================================================================== # Google Account Details # =========================================================================== # Account details for google docs email = '[email protected]' password = 'my_password' spreadsheet = 'my_spreadsheet' # =========================================================================== # Example Code # =========================================================================== # Login with your Google account try: gc = gspread.login(email, password) except: print "Unable to log in. Check your email address/password" sys.exit() # Open a worksheet from your spreadsheet using the filename try: worksheet = gc.open(spreadsheet).sheet1 # Alternatively, open a spreadsheet using the spreadsheet's key # worksheet = gc.open_by_key('0BmgG6nO_6dprdS1MN3d3MkdPa142WFRrdnRRUWl1UFE') except: print "Unable to open the spreadsheet. Check your filename: %s" % spreadsheet sys.exit() # Continuously append data while(True): # Run the DHT program to get the humidity and temperature readings! output = subprocess.check_output(["./Adafruit_DHT", "2302", "17"]); print output matches = re.search("Temp =\s+([0-9.]+)", output) if (not matches): time.sleep(3) continue temp1 = float(matches.group(1)) temp = temp1*9/5+32 # added the extra step to converto to fahrenheit # search for humidity printout matches = re.search("Hum =\s+([0-9.]+)", output) if (not matches): time.sleep(3) continue humidity = float(matches.group(1)) print "Temperature: %.1f F" % temp print "Humidity: %.1f %%" % humidity # Append the data in the spreadsheet, including a timestamp try: values = [datetime.datetime.now(), temp, humidity] worksheet.append_row(values) except: print "Unable to append data. Check your connection?" sys.exit() # Wait 30 seconds before continuing or just exit print "Wrote a row to %s" % spreadsheet # time.sleep(60) sys.exit() that's basically it. It works fine using 'sudo python script.py' as long as the Adafruit_DHT program is in the same directory. Here's the error I get: Traceback (most recent call last): File "/home/pi/Adafruit/dht/Ada_temp.py", line 44, in <module> output = subprocess.check_output(["./home/pi/Adafruit/dht/Adafruit_DHT", "2302", "17"]); File "/usr/lib/python2.7/subprocess.py", line 537, in check_output process = Popen(stdout=PIPE, *popenargs, **kwargs) File "/usr/lib/python2.7/subprocess.py", line 679, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory I've tried adding the full path of the c program (Adafruit_DHT), to no avail... Answer: Locate the problem. 1. Does the script run at all? Do something trivial in the first line of the script to see that it actually gets executed from **cron** (e.g.: write to a file in /tmp). 2. Once you managed to run it, look for other problems. Cron can be set up to send the a mail with the output of the script. One obvious thing I see is: `./Adafruit_DHT`, relative path is used, that's a bad sign, the cron script is probably not executed in the directory you think it does. Fix it (= use absolute path).
What is the main use of the Python built-in 'compile'? Question: When looking through the list of [Python built- in](http://docs.python.org/2/library/functions.html#locals) functions, I struggle with understanding the usefulness the method [`compile`](http://docs.python.org/2/library/functions.html#compile). All of the examples I could find point to a simple "hello world". It make sense _what_ it does, but not _when_ to use it. Is this the same method Python uses to generate the .pyc files? Can this be used to remove some of the dynamic nature of Python to improve performance on certain blocks of code? (Knowing full well that a module in C is the way to go precompiled modules.) Answer: From here: [What's the difference between eval, exec, and compile in Python?](http://stackoverflow.com/questions/2220699/whats-the-difference- between-eval-exec-and-compile-in-python): `compile` is a lower level version of `exec` and `eval`. It does not execute or evaluate your statements or expressions, but returns a code object that can do it. The modes are as follows: 1. `compile(string, '', 'eval')` returns the code object that would have been executed had you done `eval(string)`. Note that you _cannot_ use statements in this mode; only a (single) expression is valid. 2. `compile(string, '', 'exec')` returns the code object that would have been executed had you done `exec(string)`. You can use any number of statements here. 3. `compile(string, '', 'single')` is like the `exec` mode, but it will ignore everything except for the first statement. Note that an `if`/`else` statement with its results is considered a single statement. UPDATE: _**When to compile Python?_** Generally you compile Python to take advantage of performance. Compiled code has a much faster startup time since it doesn't have to be compiled, but **it doesn't run any faster**. Most notably, you would use `compile` if you want to **convert code into bytecode by hand**. This brings up another important, but pertinent question **why** do this? As referenced in this [magnificent article](http://lucumr.pocoo.org/2011/2/1/exec-in-python/): > if you want to use exec and you plan on executing that code more than once, > make sure you compile it into bytecode first and then execute that bytecode > only and only in a new dictionary as namespace. Of particular note is this: > Now how much faster is executing bytecode over creating bytecode and > executing that?: > > $ python -mtimeit -s 'code = "a = 2; b = 3; c = a * b"' 'exec code' 10000 > loops, best of 3: 22.7 usec per loop > > $ python -mtimeit -s 'code = compile("a = 2; b = 3; c = a * b", > "", "exec")' 'exec code' 1000000 loops, best of 3: 0.765 usec per loop > > **32 times as fast for a very short code example.** It becomes a lot worse > the more code you have. Why is that the case? **Because parsing Python code > and converting that into Bytecode is an expensive operation compared to > evaluating the bytecode.** That of course also affects `execfile` which > totally does not use bytecode caches, how should it. It's not gonna > magically check if there is a `.pyc` file if you are passing the path to a > `foo.py` file.
Python NameError in script Question: I am having issues with this multiprocess script I modeled it after the one I found here <http://broadcast.oreilly.com/2009/04/pymotw-multiprocessing- part-2.html> class test_imports:#Test classes remove def import_1(self, control_queue, thread_number): print ("Import_1 number %d started") % thread_number run = True count = 1 while run: alive = control_queue.get() if alive == 't1kill': print ("Killing thread type 1 number %d") % thread_number run = False break print ("Thread type 1 number %d run count %d") % (thread_number, count) count = count + 1 def worker_generator(control_queue, threadName, runNum): if threadName == 'one': print ("Starting import_1 number %d") % runNum p = Process(target=test_import.import_1, args=(control_queue, runNum)) p.start() if __name__ == '__main__': # Establish communication queues control = multiprocessing.Queue() runNum = int(raw_input("Enter a number: ")) threadNum = int(raw_input("Enter number of threads: ")) threadName = raw_input("Enter number: ") thread_Count = 0 print ("Starting threads") for i in range(threadNum): worker_generator(control, threadName, i) thread_Count = thread_Count + 1 time.sleep(runNum)#let threads do their thing print ("Terminating threads") for i in range(thread_Count): control.put("t1kill") control.put("t2kill") This is the error I get when I run it: Traceback (most recent call last): File "multiQueue.py", line 62, in <module> worker_generator(control, threadName, i) File "multiQueue.py", line 34, in worker_generator p = Process(target=test_import.import_1, args=(control_queue, runNum)) NameError: global name 'Process' is not defined` I know where it is, but I took that process call from known good code so I don't think it is a syntax error. Any help? Answer: Normally this is due to a missing module import. Did you `import multiprocessing`? The code I have is: import multiprocessing import time class test_imports:#Test classes remove def import_1(self, control_queue, thread_number): print ("Import_1 number %d started") % thread_number run = True count = 1 while run: alive = control_queue.get() if alive == 't1kill': print ("Killing thread type 1 number %d") % thread_number run = False break print ("Thread type 1 number %d run count %d") % (thread_number, count) count = count + 1 def worker_generator(control_queue, threadName, runNum): if threadName == 'one': print ("Starting import_1 number %d") % runNum p = multiprocessing.Process(target=test_imports.import_1, args=(control_queue, runNum)) p.start() if __name__ == '__main__': # Establish communication queues control = multiprocessing.Queue() runNum = int(raw_input("Enter a number: ")) threadNum = int(raw_input("Enter number of threads: ")) threadName = raw_input("Enter name: ") thread_Count = 0 print ("Starting threads") for i in range(threadNum): worker_generator(control, threadName, i) thread_Count = thread_Count + 1 time.sleep(runNum)#let threads do their thing print ("Terminating threads") for i in range(thread_Count): control.put("t1kill") control.put("t2kill")
'Assertion Error' while trying to create a console screen using urwid Question: code below creates a layout and displays some text in the layout. Next the layout is displayed on the console screen using raw display module from urwid library. (More info on my complete project can be gleaned from questions at [widget advice for a console project](http://stackoverflow.com/questions/17846930/required-widgets-for- displaying-a-1d-console-application) and [urwid for a console project](http://stackoverflow.com/questions/17381319/using-urwid-to- create-a-2d-console-application). My skype help request being [here](http://stackoverflow.com/questions/17846113/widget-to-choose- for-1d-urwid-application).) However running the code fails as an Assertion Error is raised as described below : Error on running code is : ` Traceback (most recent call last): File "./yamlUrwidUIPhase6.py", line 98, in <module> main() File "./yamlUrwidUIPhase6.py", line 92, in main form.main() File "./yamlUrwidUIPhase6.py", line 48, in main self.view = formLayout() File "./yamlUrwidUIPhase6.py", line 77, in formLayout ui.draw_screen(dim, frame.render(dim, True)) File "/usr/lib64/python2.7/site-packages/urwid/raw_display.py", line 535, in draw_screen assert self._started AssertionError ` The code : import sys sys.path.append('./lib') import os from pprint import pprint import random import urwid ui=urwid.raw_display.Screen() class FormDisplay(object): def __init__(self): global ui self.ui = ui palette = ui.register_palette([ ('Field', 'dark green, bold', 'black'), # information fields, Search: etc. ('Info', 'dark green', 'black'), # information in fields ('Bg', 'black', 'black'), # screen background ('InfoFooterText', 'white', 'dark blue'), # footer text ('InfoFooterHotkey', 'dark cyan, bold', 'dark blue'), # hotkeys in footer text ('InfoFooter', 'black', 'dark blue'), # footer background ('InfoHeaderText', 'white, bold', 'dark blue'), # header text ('InfoHeader', 'black', 'dark blue'), # header background ('BigText', RandomColor(), 'black'), # main menu banner text ('GeneralInfo', 'brown', 'black'), # main menu text ('LastModifiedField', 'dark cyan, bold', 'black'), # Last modified: ('LastModifiedDate', 'dark cyan', 'black'), # info in Last modified: ('PopupMessageText', 'black', 'dark cyan'), # popup message text ('PopupMessageBg', 'black', 'dark cyan'), # popup message background ('SearchBoxHeaderText', 'light gray, bold', 'dark cyan'), # field names in the search box ('SearchBoxHeaderBg', 'black', 'dark cyan'), # field name background in the search box ('OnFocusBg', 'white', 'dark magenta') # background when a widget is focused ]) urwid.set_encoding('utf8') def main(self): global ui #self.view = ui.run_wrapper(formLayout) self.view = formLayout() self.ui.start() self.loop = urwid.MainLoop(self.view, self.palette, unhandled_input=self.unhandled_input) self.loop.run() def unhandled_input(self, key): if key == 'f8': quit() return def formLayout(): global ui text1 = urwid.Text("Urwid 3DS Application program - F8 exits.") text2 = urwid.Text("One mission accomplished") textH = urwid.Text("topmost Pile text") cols = urwid.Columns([text1,text2]) pile = urwid.Pile([textH,cols]) fill = urwid.Filler(pile) textT = urwid.Text("Display") textSH = urwid.Text("Pile text in Frame") textF = urwid.Text("Good progress !") frame = urwid.Frame(fill,header=urwid.Pile([textT,textSH]),footer=textF) dim = ui.get_cols_rows() ui.draw_screen(dim, frame.render(dim, True)) return def RandomColor(): '''Pick a random color for the main menu text''' listOfColors = ['dark red', 'dark green', 'brown', 'dark blue', 'dark magenta', 'dark cyan', 'light gray', 'dark gray', 'light red', 'light green', 'yellow', 'light blue', 'light magenta', 'light cyan', 'default'] color = listOfColors[random.randint(0, 14)] return color def main(): form = FormDisplay() form.main() ######################################## ##### MAIN ENTRY POINT ######################################## if __name__ == '__main__': main() I don't want to change the function formLayout as I intend to add more to this basic code framework, where in another function will be added that repeatedly calls formLayout to keep updating the screen based on reading values from a yml file. I already have a separate code that deals with reading the yaml file and extracting ordered dictionaries out it. After figuring out how to get basic urwid console working, I can move on to integrating both to create my final application. Answer: It means that self._started has been evaluated to False. assert <Some boolean expression>, "Message if exp is False" If the expression is evaluated to True, nothing special will happen, but if the expression is evaluated to False an AssertionError exception will be thrown. You can try/except the line if you want a cleaner message: try: assert self._started, "The screen is not up and running !" except AssertionError as e: print "Oops, something happened: " + str(e) Some documentation: <http://www.tutorialspoint.com/python/assertions_in_python.htm>
Pandas import error Question: I tried installing pandas using `easy_install` and it claimed that it successfully installed the pandas package in my Python Directory. I switch to IDLE and try `import pandas` and it throws me the following error - ` Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import pandas File "C:\Python27\lib\site- packages\pandas-0.12.0-py2.7-win32.egg\pandas\__init__.py", line 6, in <module> from . import hashtable, tslib, lib File "numpy.pxd", line 157, in init pandas.hashtable (pandas\hashtable.c:20282) ValueError: numpy.dtype has the wrong size, try recompiling ` Please help me diagnose the error. FYI: I have already installed the `numpy` package Answer: Maybe you interrupted pandas install , retry using pip : First install pip (if you haven't done it already) : easy_install pip then reinstall pandas: pip install pandas --upgrade Hope it helps
Autorun python script from python Question: I wrote a python script that downloads a random picture from [APOD](http://apod.nasa.gov/apod/astropix.html). I want to be able to specify the update frequency in python and have python automatically run the script. So the program would look something like this: //first setup print "how often should the background change in hours?" updatefrequency = input() schedule_autorun(updatefrequency) //run each time runprogram() I've seen that people have used the windows task scheduler to auto run the program, but I would like to set it from python. I am running python 2.7 on Windows 7 Answer: How about the time module? import time timeinseconds = 100000 while(1): time.sleep(timeinseconds) runProgram() If the time it takes to run the program exceeds your wait time, you can also call it as a separate process. from subprocess import call call(['python','runProgram.py']) or subprocess.Popen
Problems on installing cvxopt Question: I am trying to install cvxopt on windows, I use a 2.7 Python Enthought distribution. I followed the instructions here, <http://abel.ee.ucla.edu/cvxopt/install/> The error I run into is the follows, **./liblapack.a: could not read symbols: Archive has no index; run ranlib to add o ne collect2: ld returned 1 exit status error: command 'gcc' failed with exit status** Please help me, I am pretty lost. Thanks a lot. Answer: The best way to get this running is by installing a pre-compiled binary. First, download the [MLK build of numpy for windows](http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy). Then, download the [installer for cvxopt](http://www.lfd.uci.edu/~gohlke/pythonlibs/#cvxopt) and run it. It is very important you pick the build that corresponds to your version of Python. The builds I linked are for the standard Python for Windows. They should work with Enthought's distribution as well.
Trouble installing Python package group (STSCI) Question: I'm trying to install a set of packages called STSCI (Space Telescope Science Institute). However, I get the following error, and I'm not sure how to fix it: error: command 'gcc' failed with exit status 1 Here's the full terminal log: Requirement already satisfied (use --upgrade to upgrade): stscipython in /usr/local/lib/python2.7/dist-packages/stscipython-2.14-py2.7.egg Requirement already satisfied (use --upgrade to upgrade): d2to1>=0.2.9,<=0.2.99 in /usr/local/lib/python2.7/dist-packages/d2to1-0.2.10-py2.7.egg (from stscipython) Requirement already satisfied (use --upgrade to upgrade): stsci.distutils>=0.3.2,<=0.3.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): pyfits>=3.1.1,<=3.1.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): stsci.tools>=3.2,<=3.2.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): stsci.ndimage>=0.10.0,<=0.10.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): stsci.convolve>=2.1,<=2.1.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): pywcs>=1.10.2,<=1.10.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): stwcs>=1.1.0,<=1.1.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): stsci.stimage>=0.2,<=0.2.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): stsci.imagestats>=1.4,<=1.4.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): stsci.imagemanip>=1.1,<=1.1.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): stsci.image>=2.1,<=2.1.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): pysynphot>=0.9.5,<=0.9.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): pydrizzle>=6.4.0,<=6.4.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): nictools>=1.1.0,<=1.1.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): calcos>=2.19.7,<=2.19.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): astrolib.coords>=0.39.4,<=0.39.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): wfpc2tools>=1.0.1,<=1.0.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): wfc3tools>=1.1,<=1.1.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): stsci.sphinxext>=1.2.1,<=1.2.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): stsci.numdisplay>=1.6,<=1.6.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): stistools>=1.0.1,<=1.0.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Requirement already satisfied (use --upgrade to upgrade): reftools>=1.6.4,<=1.6.99 in /usr/local/lib/python2.7/dist-packages (from stscipython) Downloading/unpacking pyraf>=2.1,<=2.1.99 (from stscipython) Downloading pyraf-2.1.1.tar.gz (2.0MB): 2.0MB downloaded Running setup.py egg_info for package pyraf warning: no files found matching 'MANIFEST' warning: no files found matching 'pyraf_install_src.ps' under directory 'docs' warning: no files found matching 'pyraf_install_src.pdf' under directory 'docs' warning: no files found matching '*.h' under directory 'src' Downloading/unpacking opuscoords>=1.0.1,<=1.0.99 (from stscipython) Downloading opuscoords-1.0.1.tar.gz Running setup.py egg_info for package opuscoords Downloading/unpacking multidrizzle>=3.4.0,<=3.4.99 (from stscipython) Downloading multidrizzle-3.4.0.tar.gz (64kB): 64kB downloaded Running setup.py egg_info for package multidrizzle Downloading/unpacking fitsblender>=0.2,<=0.2.99 (from stscipython) Downloading fitsblender-0.2.tar.gz (64kB): 64kB downloaded Running setup.py egg_info for package fitsblender Downloading/unpacking drizzlepac>=1.1.8,<=1.1.99 (from stscipython) Downloading drizzlepac-1.1.8.tar.gz (657kB): 657kB downloaded Running setup.py egg_info for package drizzlepac Requirement already satisfied (use --upgrade to upgrade): costools>=1.1,<=1.1.99 in /usr/local/lib/python2.7/dist-packages/costools-1.1-py2.7.egg (from stscipython) Requirement already satisfied (use --upgrade to upgrade): acstools>=1.7.2,<=1.7.99 in /usr/local/lib/python2.7/dist-packages/acstools-1.7.2-py2.7-linux-i686.egg (from stscipython) Requirement already satisfied (use --upgrade to upgrade): distribute in /usr/lib/python2.7/dist-packages (from d2to1>=0.2.9,<=0.2.99->stscipython) Requirement already satisfied (use --upgrade to upgrade): numpy in /usr/lib/python2.7/dist-packages (from pyfits>=3.1.1,<=3.1.99->stscipython) Installing collected packages: pyraf, opuscoords, multidrizzle, fitsblender, drizzlepac Running setup.py install for pyraf building 'pyraf.sscanfmodule' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/X11R6/include -I/usr/include/python2.7 -c src/sscanfmodule.c -o build/temp.linux-i686-2.7/src/sscanfmodule.o src/sscanfmodule.c: In function ‘initsscanf’: src/sscanfmodule.c:443:14: warning: variable ‘m’ set but not used [-Wunused-but-set-variable] gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro build/temp.linux-i686-2.7/src/sscanfmodule.o -L/usr/X11R6/lib64 -L/usr/X11R6/lib -o build/lib.linux-i686-2.7/pyraf/sscanfmodule.so building 'pyraf.xutilmodule' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/X11R6/include -I/usr/include/python2.7 -c src/xutil.c -o build/temp.linux-i686-2.7/src/xutil.o src/xutil.c:2:19: fatal error: X11/X.h: No such file or directory compilation terminated. error: command 'gcc' failed with exit status 1 Complete output from command /usr/bin/python -c "import setuptools;__file__='/tmp/pip-build-vidur/pyraf/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-1XxMCU-record/install-record.txt --single-version-externally-managed: running install running build running build_py creating build creating build/lib.linux-i686-2.7 creating build/lib.linux-i686-2.7/pyraf copying lib/pyraf/graphcap.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/subproc.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/splash.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/gkicmd.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/irafcompleter.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/textattrib.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/urwutil.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/pyrafTk.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/fontdata.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/MplCanvasAdapter.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/generic.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/irafhelp.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/iraffunctions.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/irafdisplay.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/irafnames.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/gki_psikern_tests.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/gkitkbase.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/pyrafglobals.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/irafexecute.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/ipython_api.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/gki_sys_tests.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/irafgwcs.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/epar.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/urwfiledlg.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/gkigcur.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/GkiMpl.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/clscan.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/irafpar.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/cl2py.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/gwm.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/clcache.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/dirdbm.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/irafecl.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/msgiowidget.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/gkitkplot.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/dirshelve.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/iraf.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/gki.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/irafimport.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/iraftask.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/newWindowHack.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/filecache.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/cgeneric.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/Ptkplot.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/pycmdline.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/gkiiraf.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/msgiobuffer.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/tpar.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/aqutil.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/wutil.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/irafukey.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/cltoken.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/tkplottext.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/irafimcur.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/cllinecache.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/irafinst.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/pseteparoption.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/clparse.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/describe.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/clast.py -> build/lib.linux-i686-2.7/pyraf copying lib/pyraf/__init__.py -> build/lib.linux-i686-2.7/pyraf running build_ext running pre_hook pyraf_setup.build_ext_hook for command build_ext building 'pyraf.sscanfmodule' extension creating build/temp.linux-i686-2.7 creating build/temp.linux-i686-2.7/src gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/X11R6/include -I/usr/include/python2.7 -c src/sscanfmodule.c -o build/temp.linux-i686-2.7/src/sscanfmodule.o src/sscanfmodule.c: In function ‘initsscanf’: src/sscanfmodule.c:443:14: warning: variable ‘m’ set but not used [-Wunused-but-set-variable] gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro build/temp.linux-i686-2.7/src/sscanfmodule.o -L/usr/X11R6/lib64 -L/usr/X11R6/lib -o build/lib.linux-i686-2.7/pyraf/sscanfmodule.so building 'pyraf.xutilmodule' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/X11R6/include -I/usr/include/python2.7 -c src/xutil.c -o build/temp.linux-i686-2.7/src/xutil.o src/xutil.c:2:19: fatal error: X11/X.h: No such file or directory compilation terminated. error: command 'gcc' failed with exit status 1 So what's the easy fix for this? Answer: You need to install `libx11-dev`. Use sudo apt-get install libx11-dev
Selenium (with python) how to modify an element css style Question: I'm trying to change CSS style of an element (example: from `"visibility: hidden;"` to `"visibility: visible;"`) using selenium `.execute_script`. (any other method through selenium+python would be accepted gracefully). my code: driver = webdriver.Firefox() driver.get("http://www.example.com") elem = driver.find_element_by_id('copy_link') elem.execute_script( area of my problem ) what do i need to do in order to play with the CSS of the webpage ? Answer: Here is an example without using any jQuery. It will hide Google's logo. from selenium import webdriver driver = webdriver.Firefox() driver.get("http://www.google.com") driver.execute_script("document.getElementById('lga').style.display = 'none';") The same idea could be used to show a hidden element by setting `.style.display` to `"block"`, for example.
Fitting data using UnivariateSpline in scipy python Question: I have a experimental data to which I am trying to fit a curve using UnivariateSpline function in scipy. The data looks like: x y 13 2.404070 12 1.588134 11 1.760112 10 1.771360 09 1.860087 08 1.955789 07 1.910408 06 1.655911 05 1.778952 04 2.624719 03 1.698099 02 3.022607 01 3.303135 Here is what I am doing: import matplotlib.pyplot as plt from scipy import interpolate yinterp = interpolate.UnivariateSpline(x, y, s = 5e8)(x) plt.plot(x, y, 'bo', label = 'Original') plt.plot(x, yinterp, 'r', label = 'Interpolated') plt.show() That's how it looks: ![Curve fit](http://i.imgur.com/8rMKC3W.png) I was wondering if anyone has thought on other curve fitting options which scipy might have? I am relatively new to scipy. Thanks! Answer: There are a few issues. The first issue is the order of the x values. From the documentation for `scipy.interpolate.UnivariateSpline` we find x : (N,) array_like 1-D array of independent input data. MUST BE INCREASING. Stress added by me. For the data you have given the x is in the reversed order. To debug this it is useful to use a "normal" spline to make sure everything makes sense. The second issue, and the one more directly relevant for your issue, relates to the s parameter. What does it do? Again from the documentation we find s : float or None, optional Positive smoothing factor used to choose the number of knots. Number of knots will be increased until the smoothing condition is satisfied: sum((w[i]*(y[i]-s(x[i])))**2,axis=0) <= s If None (default), s=len(w) which should be a good value if 1/w[i] is an estimate of the standard deviation of y[i]. If 0, spline will interpolate through all data points. So s determines how close the interpolated curve must come to the data points, in the least squares sense. If we set the value very large then the spline does not need to come near the data points. As a complete example consider the following import scipy.interpolate as inter import numpy as np import pylab as plt x = np.array([13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) y = np.array([2.404070, 1.588134, 1.760112, 1.771360, 1.860087, 1.955789, 1.910408, 1.655911, 1.778952, 2.624719, 1.698099, 3.022607, 3.303135]) xx = np.arange(1,13.01,0.1) s1 = inter.InterpolatedUnivariateSpline (x, y) s1rev = inter.InterpolatedUnivariateSpline (x[::-1], y[::-1]) # Use a smallish value for s s2 = inter.UnivariateSpline (x[::-1], y[::-1], s=0.1) s2crazy = inter.UnivariateSpline (x[::-1], y[::-1], s=5e8) plt.plot (x, y, 'bo', label='Data') plt.plot (xx, s1(xx), 'k-', label='Spline, wrong order') plt.plot (xx, s1rev(xx), 'k--', label='Spline, correct order') plt.plot (xx, s2(xx), 'r-', label='Spline, fit') # Uncomment to get the poor fit. #plt.plot (xx, s2crazy(xx), 'r--', label='Spline, fit, s=5e8') plt.minorticks_on() plt.legend() plt.xlabel('x') plt.ylabel('y') plt.show() ![Result from example code](http://i.stack.imgur.com/OyZ0G.png)
PyQt: RuntimeError: wrapped C/C++ object has been deleted Question: If I run this code: #!/usr/local/bin/ python3 import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class Window(QMainWindow): def __init__(self): super().__init__() self.button1 = QPushButton("1") self.button2 = QPushButton("2") self.setCentralWidget(self.button1) self.button1.clicked.connect(lambda: self.setCentralWidget(self.button2)) self.button2.clicked.connect(lambda: self.setCentralWidget(self.button1)) self.show() if __name__ == '__main__': import sys app = QApplication(sys.argv) window = Window() sys.exit(app.exec_()) ...I get this output: Traceback (most recent call last): File "test.py", line 16, in <lambda> self.button2.clicked.connect(lambda: self.setCentralWidget(self.button1)) RuntimeError: wrapped C/C++ object of type QPushButton has been deleted I do not understand why the object is being deleted. Window should maintain a reference to it. I have thoroughly investigated these posts: [Understanding the “underlying C/C++ object has been deleted” error](http://stackoverflow.com/questions/6002895/understanding-the- underlying-c-c-object-has-been-deleted-error) [Can a PyQt4 QObject be queried to determine if the underlying C++ instance has been destroyed?](http://stackoverflow.com/questions/5122451/can-a-pyqt4-qobject-be- queried-to-determine-if-the-underlying-c-instance-has-b?rq=1) Why is the button being deleted? Answer: This answer to this question is as found here: [Python PySide (Internal c++ Object Already Deleted)](http://stackoverflow.com/questions/5339062/python- pyside-internal-c-object-already-deleted) Apparently, assigning one widget to QMainWindow using setCentralWidget and then assigning another widget with setCentralWidget will cause the underlying c++ QWidget to be deleted, even though I have an object that maintains reference to it. > Note: QMainWindow takes ownership of the widget pointer and deletes it at > the appropriate time.
What's the right form of python interpreter? Question: I just began to learn Python for not long and I tried to run a very simple python CGI script. The html code is <form action='cgi-bin/hello_get.py' method = 'post'> Name: <input type = 'text' name = 'name'> <br/> <input type = 'submit' value='Submit'/> </form> and the 'hello_get.py' file is #!c:/Python27/python.exe import cig, cgitb form = cgi.FieldStorage() name = form.getvalue('name') print "Content-type:text/html\r\n\r\n" print "<html>" print "<head>" print "<title>Hello - Second CGI Program</title>" print "</head>" print "<body>" print "<h2>Hello %s </h2> % (name)" print "</body>" print "</html>" However, everytime I tried it on the browser, after I press Submit, the reply was the whole 'hello_get.py' file. The page just show the whole content of 'hello_get.py' file. Like this <http://i.imgur.com/ogUcE0l.jpg> So where did I go wrong? It should be very simple.I thought the form of the path of python interpreter was wrong, but I have tried several ways and nothing worked. Thanks!!! Answer: Your first print line ends with a double quote instead of a single quote. Change it to this: print 'Content-type:text/html\r\n\r\n' EDIT After looking at an example online, that first line should be surrounded by double quotes, so print "Content-type:text/html\r\n\r\n"
Python Tkinter save canvas as image using PIL Question: I have this code which lets the user draw on the canvas and save it as a `jpeg` file. As mentioned in [this post](http://stackoverflow.com/questions/9886274/how- can-i-convert-canvas-content-to-an-image), I tried to draw in parallel on the canvas and in memory using the PIL so that I can save it as a `jpeg` instead of `postscript`. It seemed to be working until I found out that some of the images I saved with PIL are not the same as what was drawn on the canvas. I assume `canvas.create_line` and `draw.line` from the PIL image draw module function similarly and should give similar output. Below is what went wrong: For example, when I draw a "T" it seems alright (Left is my drawing, right is the saved image). ![enter image description here](http://i.stack.imgur.com/iutdf.jpg)![enter image description here](http://i.stack.imgur.com/d43X5.jpg) But when I draw an "A" , the output image seems a bit weird. ![enter image description here](http://i.stack.imgur.com/S881u.jpg)![enter image description here](http://i.stack.imgur.com/k14nH.jpg) This is my current code: import Tkinter as tk import Image,ImageDraw class ImageGenerator: def __init__(self,parent,posx,posy,*kwargs): self.parent = parent self.posx = posx self.posy = posy self.sizex = 200 self.sizey = 200 self.b1 = "up" self.xold = None self.yold = None self.coords= [] self.drawing_area=tk.Canvas(self.parent,width=self.sizex,height=self.sizey) self.drawing_area.place(x=self.posx,y=self.posy) self.drawing_area.bind("<Motion>", self.motion) self.drawing_area.bind("<ButtonPress-1>", self.b1down) self.drawing_area.bind("<ButtonRelease-1>", self.b1up) self.button=tk.Button(self.parent,text="Done!",width=10,bg='white',command=self.save) self.button.place(x=self.sizex/7,y=self.sizey+20) self.button1=tk.Button(self.parent,text="Clear!",width=10,bg='white',command=self.clear) self.button1.place(x=(self.sizex/7)+80,y=self.sizey+20) self.image=Image.new("RGB",(200,200),(255,255,255)) self.draw=ImageDraw.Draw(self.image) def save(self): print self.coords self.draw.line(self.coords,(0,128,0),width=3) filename = "temp.jpg" self.image.save(filename) def clear(self): self.drawing_area.delete("all") self.coords=[] def b1down(self,event): self.b1 = "down" def b1up(self,event): self.b1 = "up" self.xold = None self.yold = None def motion(self,event): if self.b1 == "down": if self.xold is not None and self.yold is not None: event.widget.create_line(self.xold,self.yold,event.x,event.y,smooth='true',width=3,fill='blue') self.coords.append((self.xold,self.yold)) self.xold = event.x self.yold = event.y if __name__ == "__main__": root=tk.Tk() root.wm_geometry("%dx%d+%d+%d" % (400, 400, 10, 10)) root.config(bg='white') ImageGenerator(root,10,10) root.mainloop() Where did I go wrong and what should I do to save the exact same picture that is drawn on the canvas as a jpeg image? Answer: I managed to solved my problem.In fact i was just being dumb. Even though `canvas.create_line` and `draw.line` have the similar function, i didn't use the same exact data to draw out both images. after making changes, this is my working code. import Tkinter as tk import Image,ImageDraw class ImageGenerator: def __init__(self,parent,posx,posy,*kwargs): self.parent = parent self.posx = posx self.posy = posy self.sizex = 200 self.sizey = 200 self.b1 = "up" self.xold = None self.yold = None self.drawing_area=tk.Canvas(self.parent,width=self.sizex,height=self.sizey) self.drawing_area.place(x=self.posx,y=self.posy) self.drawing_area.bind("<Motion>", self.motion) self.drawing_area.bind("<ButtonPress-1>", self.b1down) self.drawing_area.bind("<ButtonRelease-1>", self.b1up) self.button=tk.Button(self.parent,text="Done!",width=10,bg='white',command=self.save) self.button.place(x=self.sizex/7,y=self.sizey+20) self.button1=tk.Button(self.parent,text="Clear!",width=10,bg='white',command=self.clear) self.button1.place(x=(self.sizex/7)+80,y=self.sizey+20) self.image=Image.new("RGB",(200,200),(255,255,255)) self.draw=ImageDraw.Draw(self.image) def save(self): filename = "temp.jpg" self.image.save(filename) def clear(self): self.drawing_area.delete("all") self.image=Image.new("RGB",(200,200),(255,255,255)) self.draw=ImageDraw.Draw(self.image) def b1down(self,event): self.b1 = "down" def b1up(self,event): self.b1 = "up" self.xold = None self.yold = None def motion(self,event): if self.b1 == "down": if self.xold is not None and self.yold is not None: event.widget.create_line(self.xold,self.yold,event.x,event.y,smooth='true',width=3,fill='blue') self.draw.line(((self.xold,self.yold),(event.x,event.y)),(0,128,0),width=3) self.xold = event.x self.yold = event.y if __name__ == "__main__": root=tk.Tk() root.wm_geometry("%dx%d+%d+%d" % (400, 400, 10, 10)) root.config(bg='white') ImageGenerator(root,10,10) root.mainloop()
Raspberry Pi + PocketSphinx Question: I am attempting to develop a python application on Windows 8 using Eclipse (Juno) IDE with PyDev plugin. I have my environment set up, with interpreter. Able to run basics like "hello, world!" I would like to start working with CMUSphinx (Namely pocketsphinx & sphinxbase) to do some voice recognition on the Raspberry Pi (Raspbian, latest), but do not know how to import pocketsphinx and sphinxbase as usable libraries in Windows 8 so that I am able to import them in the Python script and use them like so: import sphinxbase import pocketsphinx I also need to know that if I build my application while importing these two libraries, if the libraries will become part of the application and will be packaged with it so that it will run natively on my Raspberry Pi (Raspbian, latest) without me having to install and associate the libraries with my Pi. Answer: You need to separate two different issues - running pocketsphinx on Windows with Python and running pocketsphinx on Raspberry Pi with Python. To run pocketsphinx on Windows with python you need to compile and install python module for Windows. You can do that with the python script python/setup_win32.py. Before running this script you need to compile pocketsphinx first according to the instructions. This script will compile and install python module into required place. For more information on this script read python distutils documentation. To use pocketsphinx python module on Raspberry Pi which is a normal Linux system you can just compile and install pocketsphinx according to the documentation with standard configure && make && make install. The python module will be compiled automatically and should work as expected. For more information about Python modules please read the documentation: [Python documentation on modules and packages](http://docs.python.org/2/tutorial/modules.html#packages) [How do I install Python packages on Windows?](http://stackoverflow.com/questions/1449494/how-do-i-install-python- packages-on-windows)
null value in JSON is not interpreted by python for openstack API Question: I am using OpenStack's REST API for programmatic implementation of start or stop server. The link for API reference is <http://api.openstack.org/api-ref.html#ext-os- server-start-stop> This requires a dictionary in python as follows: dict = { os-start:null } Then I am doing a json.dumps(dict) and making a post request to the openstack's public URL for nova module. When I run this program ,error of unknown global name "null". Hence, its not working. I want to know for this request of starting the server on OpenStack to work , what should I use as the value of field "os-start" in request JSON. Let me know if any additional information is needed. Thank you in advance. Answer: Python's `None` singleton is translated to a JSON `null`, and vice versa. Use that instead: >>> import json >>> json.dumps({'os-start': None}) '{"os-start": null}' >>> json.loads('{"os-start": null}') {u'os-start': None}
AttributeError: '_socketobject' object has no attribute 'bind' Question: here is my code: import sae import socket, sys host = '' port = 5005 def app(environ, start_response): status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) s.listen(2) while 1: client, addr = s.accept(); print("Got connection from ", addr); while 1: print("the word you want to send:") buf = sys.stdin.readline().strip() if not buf: break client.send(bytes(buf, 'UTF-8')) data = client.recv(1024); if data: print(data) return ['Hello, world!'] application = sae.create_wsgi_app(app) but I am getting an Attribute Error that says: Traceback (most recent call last): File "/usr/local/sae/python/lib/python2.7/site-packages/sae/__init__.py", line 18, in new_app return app(environ, start_response) File "/data1/www/htdocs/850/love2note/1/index.wsgi", line 11, in app s.bind((host, port)) AttributeError: '_socketobject' object has no attribute 'bind' I really do not understand what I need to do to solve this issue. If anyone can please help me, I'll be really grateful. Answer: `import sae` you mean [Sina App Engine](http://sae.sina.com.cn/)? if True: bind is not allowed by SAE. [API](http://sae.sina.com.cn/doc/python/socket.html#api)
Python: Playing a music in the background? Question: I am currently making a game in Python. I am not using PyGame, just the console (non-GUI) When you start the game, you will get the logo to the game, and a lot of information about the "journey" you just started. There is a lot of text, so while the text is scrolling, I want to have a song played in the background. I start the music with the following code: def new_game(): import winsound winsound.PlaySound("intro.wav", winsound.SND_ALIAS) LVL1_INTRO() The only problem is: it won't continue to LVL1_INTRO() until the music have stopped playing. It's a problem, as the music is approximately 1-2 minutes long. Is there any way to fix this? After the music have started, it will continue with LVL1_INTRO() If it is possible, I would be happy if there is a code for stopping the music as well, so I don't need to start cutting the music, and make it exactly the same lenght as the intro. Thank you very much! Answer: According to the [documentation](http://docs.python.org/2/library/winsound.html#winsound.SND_ASYNC) you use the SND_ASYNC flag. winsound.SND_ASYNC Return immediately, allowing sounds to play asynchronously. To stop playing, call `PlaySound` with a `NONE` argument. winsound.PlaySound(None, winsound.SND_ASYNC)
Listening on port being used Question: Is there any way to listen to traffic on a specific port that another program is currently using, through the python `socket` module? For example: |--> my program external request -> Host ->|--> intended program I am not looking to send back a response to the request, I simply want the traffic. I was looking at using the `socket.SO_REUSEADDR` method, but I think that's simply to avoid having to wait for the socket's timeout, not to allow another listener. Answer: You can do that with [scapy](http://www.secdev.org/projects/scapy/) see <http://www.secdev.org/projects/scapy/doc/usage.html#sniffing> to use it in your own python program, you'd have to import the sniff command from scapy.all import sniff a=sniff("tcp and port 1337") sniff has various options (callback functions, timeout, number of packets etc)
Downloaded webpage looks different than the original webpage Question: I am thinking of downloading [cplusplus.com's C library](http://www.cplusplus.com/reference/clibrary/) by using Python. I want to download it completely and then convert it into a linked document such as Python documentation. This is my initial attempt at downloading the front page. #! python3 import urllib.request filehandle = urllib.request.urlopen('http://www.cplusplus.com/reference/clibrary/') with open('test.html', 'w+b') as f: for line in filehandle: f.write(line) filehandle.close() The front page is being downloaded correctly but its look is quite different than in the original webpage. By different look I mean that the nice looking formatting on the original webpage is gone after I ran the script to download the webpage. What's the reason for this? * * * Can someone explain the downvotes? What's the problem? Newbie questions not allowed? Answer: This occurs because your scraped version doesn't include the Cascading Style Sheets (CSS) linked to by the page. It also won't include any images or javascript linked to either. If you want to obtain the linked files, you'll have to parse the source code you scrape for them.
Speeding up Python Imports Question: I have a large program that is structured using object oriented techniques, and I have one main driver module that imports a bunch of other classes, which they in turn import more python built-in modules or other classes. All together I would say there is well over 250 `from x import y statements` (I don't have control over this part of the code), some are duplicates in other classes and some are unique. I profiled my code and as I suspected the majority of the time is in the start up with import so many modules and classes. There is a way to speed up this? Answer: [You can move the import statements to inside your functions to reduce initial startup.](http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Import_Statement_Overhead) Another technique would be to copy your modules to a ramdisk or tmpfs for faster IO (these use RAM, which runs much faster).
Python list simultaneous update Question: This seems to be a gotcha for me, I couldnt figure this out >>> from collections import Counter >>> tree = [Counter()]*3 >>> tree [Counter(), Counter(), Counter()] >>> tree[0][1]+=1 >>> tree [Counter({1: 1}), Counter({1: 1}), Counter({1: 1})] Why does updating one Counter updates everything? Answer: Using `[x] * 3`, the list references same item(`x`) three times. >>> from collections import Counter >>> tree = [Counter()] * 3 >>> tree[0] is tree[1] True >>> tree[0] is tree[2] True >>> another_counter = Counter() >>> tree[0] is another_counter False >>> for counter in tree: print id(counter) ... 40383192 40383192 40383192 Use list comprehension as Waleed Khan commented. >>> tree = [Counter() for _ in range(3)] >>> tree[0] is tree[1] False >>> tree[0] is tree[2] False >>> for counter in tree: print id(counter) ... 40383800 40384104 40384408
How do I import .pyx in python Question: I have been working with a project that have .pyx files and When I run it on Ninja Ide it's doesn't recognise them! How can I solve this? I have installed cython but nothing! Thank you! Answer: You need to add [this](http://docs.cython.org/src/userguide/tutorial.html#pyximport-cython- compilation-the-easy-way) before you can import `.pyx` files: import pyximport pyximport.install()
Python Memory Error when using random.sample() Question: OK, so I have a problem that I really need help with. My program reads values from a pdb file and stores those values in (array = []) I then take every combination of 4 from this arrangement of stored values and store this in a list called maxcoorlist. Because the list of combinations is such a large number, to speed things up I would like to simply take a sample of 1000-10000 from this list of combinations. However, in doing so I get a memory error on the very line that takes the random sample. MemoryError Traceback (most recent call last) <ipython-input-14-18438997b8c9> in <module>() 77 maxcoorlist= itertools.combinations(array,4) 78 random.seed(10) ---> 79 volumesample= random_sample(list(maxcoorlist), 1000) 80 vol_list= [side(i) for i in volumesample] 81 maxcoor=max(vol_list) MemoryError: It is important that I use random.seed() in this code as well, as I will be taking other samples with the seed. Answer: As mentioned in the other answers, the list() call is running you out of memory. Instead, first iterate over maxcoorlist in order to find out its length. Then create random numbers in the range [0, length) and add them to an index set until the length of the index set is 1000. Then iterate through maxcoorlist again and add the current value to a sample set if the current index is in your index set. **EDIT** An optimization is to directly calculate the length of maxcoorlist instead of iterating over it: import math n = len(array) r = 4 length = math.factorial(n) / math.factorial(r) / math.factorial(n-r)
Which module should contain logging.config.dictConfig(my_dictionary)? What about my_dictionary? Question: This is all Python. I am still learning... I have written two modules for my Python application: `Module1` and `Module2`. I need to send my logging results to three different files. `Module1` sends to `setup.log` and `setupdetails.log` files and `Module2` sends to `runall.log` Module2 is the application I run. Within it is an import statement that calls Module1. Because I have configured my logging in a `my_dictionary`, which one of the modules should contain the dictionary? Which one of the modules should contain the `logging.config.dictConfig(my_dictionary)` function? Do you know of anywhere I could find a good script with an example of how to use `dictConfig`? Answer: So, I just finally figured it out. It all works well if one puts the dictionary in the child module `Module 1` (and set `Propagate: True`). MY_DICTIONARY = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)-8s %(asctime)s %(module)s %(process)d %(thread)d %(message)s', 'datefmt': '%a, %d %b %Y %H:%M:%S' }, 'standard': { 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s', 'datefmt': '%a, %d %b %Y %H:%M:%S' }, 'simple': { 'format': '%(asctime)s %(levelname)-8s %(message)s', 'datefmt': '%a, %d %b %Y %H:%M:%S' } #etc. } } Followed by the following calls: logging.config.dictConfig(MY_DICTIONARY) vmrunalllogger = logging.getLogger('VMRunAll_Python_Logger') Then in Module 2 (the parent module), have this: logging.config.dictConfig(MY_DICTIONARY) mylogger = logging.getLogger('RunAll_Logger') I could not find specific examples that showed two different modules logging to multiple files like mine is doing, but information from multiple sources like the following helped: 1. [From the Python documentation](http://docs.python.org/2/library/logging.config.html) 2. [Another question on Stackoverflow.com](http://stackoverflow.com/questions/10931423/using-dictconfig-in-python-logging-need-to-create-a-logger-with-a-different-fil) 3. [And the examples of in the cookbook](http://docs.python.org/2/howto/logging-cookbook.html)
how to parse through this xml? Question: Suppose I have the following XML response from mediawiki api. I want to find out the earliest date that the wiki topic was revised, which in this case is 2005-08-23. How do I parse through the xml to find that out. I'm using python btw. <?xml version="1.0"?> <api> <query-continue> <revisions rvcontinue="46214352" /> </query-continue> <query> <pageids> <id>2516600</id> </pageids> <pages> <page pageid="2516600" ns="0" title="!Kung language"> <revisions> <rev timestamp="2005-08-23T00:58:40Z" /> <rev timestamp="2005-08-23T01:01:00Z" /> <rev timestamp="2005-09-02T07:21:37Z" /> <rev timestamp="2005-09-02T07:24:28Z" /> <rev timestamp="2006-01-06T07:45:35Z" /> <rev timestamp="2006-03-22T09:03:23Z" /> <rev timestamp="2006-03-30T05:50:12Z" /> <rev timestamp="2006-03-30T20:33:22Z" /> <rev timestamp="2006-03-30T20:35:05Z" /> <rev timestamp="2006-03-30T20:37:16Z" /> </revisions> </page> </pages> </query> </api> I tried the following revisions = text.getElementsByTagName("revisions") for x in revisions: children = x.childNodes for y in children: print y.nodeValue but all this does is print None. Answer: I would use lxml with an XPath expression: from lxml import etree root = etree.fromstring(xml) timestamps = root.xpath('//rev/@timestamp') As for your code, you aren't getting the attribute of the element. To do that, use `getAttribute`: print y.getAttribute('timestamp')
Python 3: Store the contents of a file into one big string Question: Suppose I have a textfile with this content: > Hello World My name is Sam > > I am 12 years old and a boy > > I like Pizza And I wanted to store it into one big string, no newlines, no spaces or anything so it would read like this: > HelloWorldMynameisSamIam12yearsoldandaboyIlikePizza How would I do that? Google hasn't been much help. Answer: You could use a regex, eg: import re with open('input') as fin: long_string = re.sub(r'\W', '', fin.read()) # HelloWorldMynameisSamIam12yearsoldandaboyIlikePizza Note that `\W` is equiv. to `[^a-zA-Z0-9_]` so you could change it to `[^a-zA-Z0-9]` if you wanted to be explicit about anything that's a non ascii letter/digit.
how to grab a web image which has a dynamic src ID in python Question: it is not a static url but a address like xxx.xxx.com/xxx/run the image is dynamically built based on daily status, so I can't grab it using its URL is it possible to stimulate a browser and get the whole page contains the image? if then how? thanks~ Answer: There's two ways of doing this. 1. Use something like [Requests](http://docs.python-requests.org/en/latest/) to grab the HTML of the page that your image is on, and then use something like [pyquery](http://pythonhosted.org/pyquery/) to parse the HTML and find the URL of your image. This should work in most cases, except when the URL isn't actually in the page's HTML (i.e. because it's put there by Javascript). 2. Use something like [Splinter](http://splinter.cobrateam.info/), which lets you programmatically control an actual browser, to grab the URL. This is a bit more of a heavyweight solution, but it runs javascript like a normal browser (because it is). The first option might look like this: import requests from pyquery import PyQuery html = requests.get('http://example.com/').text html_q = PyQuery(html) image_url = html_q('img.my_image_class').attr('src') Whereas the second might look like this: from splinter import Browser with Browser() as b: b.visit('http://example.com/') image_url = b.find_by_css('img.my_image_class')['src'] Then, just download that URL as you would normally. * * * Edit: Here's another example with Requests, this time using a session to store cookies set by a login form. You'll have to get the URL and the keys for the data dictionary from the `<form>` and `<input>` elements on the login form; they won't always be `username` and `password`. import requests s = requests.session() s.post('https://example.com/dologin', data={'username': 'adam', 'password': 'hunter2'}) html = s.get('https://example.com/other_page').text # and continue as in the first example
Python regex to match all words in {} Question: I need regex in python to get all words that are in {} for example a = 'add {new} sentence {with} this word' Result with re.findall should be [new, with] Thanks Answer: Try this: >>> import re >>> a = 'add {new} sentence {with} this word' >>> re.findall(r'\{(\w+)\}', a) ['new', 'with'] Another approach using `Formatter`: >>> from string import Formatter >>> a = 'add {new} sentence {with} this word' >>> [i[1] for i in Formatter().parse(a) if i[1]] ['new', 'with'] Another approach using `split()`: >>> import string >>> a = 'add {new} sentence {with} this word' >>> [x.strip(string.punctuation) for x in a.split() if x.startswith("{") and x.endswith("}")] ['new', 'with'] You can even use `string.Template`: >>> class MyTemplate(string.Template): ... pattern = r'\{(\w+)\}' >>> a = 'add {new} sentence {with} this word' >>> t = MyTemplate(a) >>> t.pattern.findall(t.template) ['new', 'with']
Some crazy code and crazy data. Insert rows in mysql db (python) Question: I'm trying to insert some data (stored in a list of tuples) to my local database. The data is a little inconsistent - some timestamps are `datetime.datetime` while some can be strings. But I don't think that's where my problem is. First of all, my db schema: +-----------------------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------------------------+-------------+------+-----+---------+-------+ | store | varchar(11) | NO | | NULL | | | order_no | int(11) | NO | | NULL | | | product_name | text | YES | | NULL | | | product_id | int(11) | NO | | NULL | | | classification | int(11) | NO | | NULL | | | order_date | datetime | NO | | NULL | | | power_complete_time | datetime | YES | | NULL | | | stockout_date | datetime | YES | | NULL | | | wfi_status | tinyint(4) | YES | | NULL | | | qc_status | varchar(12) | YES | | NULL | | | scanned_for_shipment_date | datetime | YES | | NULL | | | order_delivered_date | datetime | YES | | NULL | | | status | varchar(50) | YES | | NULL | | | stock_out_status | varchar(50) | YES | | NULL | | | actual_order_date | datetime | NO | | NULL | | | order_for_today | tinyint(1) | YES | | NULL | | | dispatched_within_same_day | tinyint(1) | YES | | NULL | | | stockout_within_same_day | tinyint(1) | YES | | NULL | | | order_for_yesterday | tinyint(1) | YES | | NULL | | | dispatched_within_yesterday | tinyint(1) | YES | | NULL | | | stockout_within_yesterday | tinyint(1) | YES | | NULL | | | eyeframe_less_than_1_pm | tinyint(1) | YES | | NULL | | +-----------------------------+-------------+------+-----+---------+-------+ Next up, my script with the crazy weird data. Again, the data about some dates can be inconsistent that is why I'm testing with a bunch of data rows: import MySQLdb import datetime if __name__ == '__main__': rows = [ (u'Lenskart', u'1200667194', u'Prescription Card', u'41420', u'shipping_accessories', datetime.datetime(2013, 7, 27, 4, 12, 56), datetime.datetime(2013, 7, 27, 11, 18, 4), datetime.datetime(2013, 7, 27, 11, 45, 32), u'0', None, datetime.datetime(2013, 7, 28, 3, 24, 17), u'0000-00-00 00:00:00', u'complete', None, datetime.datetime(2013, 7, 27, 9, 42, 56), 0, None, None, 0, None, None, 0), (u'Lenskart', u'1200667195', u'Rs.1800 Coupon Booklet ( Rs. 500 Coupons) - FREE', u'39799', u'shipping_accessories', datetime.datetime(2013, 7, 27, 4, 13, 17), datetime.datetime(2013, 7, 27, 10, 10, 2), datetime.datetime(2013, 7, 27, 10, 53, 32), u'1', None, datetime.datetime(2013, 7, 27, 12, 12, 2), u'0000-00-00 00:00:00', u'complete', u'complete', datetime.datetime(2013, 7, 27, 9, 43, 17), 0, None, None, 0, None, None, 0), (u'Lenskart', u'1200667196', u'Vincent Chase RG 172 Gunmetal C3 Eyeglasses', u'58131', u'eyeframe', datetime.datetime(2013, 7, 27, 4, 13, 31), datetime.datetime(2013, 7, 27, 10, 10, 2), datetime.datetime(2013, 7, 27, 12, 54, 34), u'1', None, datetime.datetime(2013, 7, 28, 4, 49, 13), u'0000-00-00 00:00:00', u'complete', None, datetime.datetime(2013, 7, 27, 9, 43, 31), 0, None, None, 0, None, None, 0), (u'Lenskart', u'1200667193', u'Prescription Card', u'41420', u'shipping_accessories', datetime.datetime(2013, 7, 27, 4, 11, 10), datetime.datetime(2013, 7, 27, 10, 12, 4), datetime.datetime(2013, 7, 27, 11, 37, 47), u'0', None, datetime.datetime(2013, 7, 27, 19, 51, 13), u'2013-07-29 00:00:00', u'delivered', None, datetime.datetime(2013, 7, 27, 9, 41, 10), 0, None, None, 0, None, None, 0), (u'Lenskart', u'1200667193', u'Prescription-Lens PC SV Regular', u'45081', u'prescription_lens', datetime.datetime(2013, 7, 27, 4, 11, 10), datetime.datetime(2013, 7, 27, 10, 12, 4), datetime.datetime(2013, 7, 27, 17, 51, 33), u'0', None, datetime.datetime(2013, 7, 27, 19, 51, 13), u'2013-07-29 00:00:00', u'delivered', None, datetime.datetime(2013, 7, 27, 9, 41, 10), 0, None, None, 0, None, None, 0), (u'Lenskart', u'1200667190', u'Rs.1800 Coupon Booklet ( Rs. 500 Coupons) - FREE', u'39799', u'shipping_accessories', datetime.datetime(2013, 7, 27, 4, 10, 33), datetime.datetime(2013, 7, 27, 10, 7, 4), datetime.datetime(2013, 7, 27, 10, 56, 2), u'1', None, datetime.datetime(2013, 7, 27, 14, 33, 21), u'0000-00-00 00:00:00', u'complete', u'complete', datetime.datetime(2013, 7, 27, 9, 40, 33), 0, None, None, 0, None, None, 0), (u'Lenskart', u'1200667187', u'Prescription-Lens CR SV Regular', u'45073', u'prescription_lens', datetime.datetime(2013, 7, 27, 4, 8, 48), datetime.datetime(2013, 7, 27, 9, 58, 2), datetime.datetime(2013, 7, 27, 12, 11, 25), u'0', None, datetime.datetime(2013, 7, 27, 17, 0, 1), u'2013-07-30 00:00:00', u'delivered', None, datetime.datetime(2013, 7, 27, 9, 38, 48), 0, None, None, 0, None, None, 0), (u'Lenskart', u'1200667183', u'Rs.1800 Coupon Booklet ( Rs. 500 Coupons) - FREE', u'39799', u'shipping_accessories', datetime.datetime(2013, 7, 27, 4, 3, 46), datetime.datetime(2013, 7, 27, 11, 44, 3), datetime.datetime(2013, 7, 27, 12, 26, 48), u'1', None, datetime.datetime(2013, 7, 27, 17, 46, 17), u'2013-07-30 00:00:00', u'delivered', None, datetime.datetime(2013, 7, 27, 9, 33, 46), 0, None, None, 0, None, None, 0), (u'Lenskart', u'1200667183', u'Prescription-Lens CR SV Regular', u'45073', u'prescription_lens', datetime.datetime(2013, 7, 27, 4, 3, 46), datetime.datetime(2013, 7, 27, 11, 44, 3), datetime.datetime(2013, 7, 27, 13, 50, 35), u'0', None, datetime.datetime(2013, 7, 27, 17, 46, 17), u'2013-07-30 00:00:00', u'delivered', None, datetime.datetime(2013, 7, 27, 9, 33, 46), 0, None, None, 0, None, None, 0), (u'Lenskart', u'1200667175', u'Bausch & Lomb Soflens 59 (6 Lenses/box)_S:-4.75 / C:0.00 / A:0 / BC:8.60 / AP:0.00 / CL:', u'90000443', u'contact_lens', datetime.datetime(2013, 7, 27, 3, 58, 6), datetime.datetime(2013, 7, 27, 9, 38, 2), datetime.datetime(2013, 7, 27, 10, 10, 22), u'0', None, datetime.datetime(2013, 7, 27, 12, 32, 17), u'2013-07-29 00:00:00', u'delivered', u'complete', datetime.datetime(2013, 7, 27, 9, 28, 6), 0, None, None, 0, None, None, 0), (u'Lenskart', u'1200667171', u'Rs.1800 Coupon Booklet ( Rs. 500 Coupons) - FREE', u'39799', u'shipping_accessories', datetime.datetime(2013, 7, 27, 3, 55, 56), datetime.datetime(2013, 7, 27, 9, 37, 3), datetime.datetime(2013, 7, 27, 9, 51, 47), u'1', None, datetime.datetime(2013, 7, 27, 12, 59, 50), u'0000-00-00 00:00:00', u'complete', u'complete', datetime.datetime(2013, 7, 27, 9, 25, 56), 0, None, None, 0, None, None, 0), (u'Lenskart', u'1200667165', u'Rs.1800 Coupon Booklet ( Rs. 500 Coupons) - FREE', u'39799', u'shipping_accessories', datetime.datetime(2013, 7, 27, 9, 20), datetime.datetime(2013, 7, 27, 9, 30, 4), datetime.datetime(2013, 7, 27, 10, 24, 35), u'1', None, datetime.datetime(2013, 7, 27, 16, 15, 14), u'2013-07-29 00:00:00', u'delivered', u'complete', datetime.datetime(2013, 7, 27, 14, 50), 0, None, None, 0, None, None, 0), (u'Bagskart', u'1200667151', u'Feelgood Backpack FG011-A Navy Blue', u'35607', u'Backpacks', datetime.datetime(2013, 7, 27, 2, 14, 52), u'', datetime.datetime(2013, 7, 27, 12, 50, 15), u'1', None, datetime.datetime(2013, 7, 27, 15, 16, 32), u'2013-07-29 00:00:00', u'delivered', u'complete', datetime.datetime(2013, 7, 27, 7, 44, 52), 0, None, None, 0, None, None, 0), (u'Lenskart', u'1200667148', u'Rs.1800 Coupon Booklet ( Rs. 500 Coupons) - FREE', u'39799', u'shipping_accessories', datetime.datetime(2013, 7, 27, 2, 8, 40), datetime.datetime(2013, 7, 27, 7, 41, 3), datetime.datetime(2013, 7, 27, 7, 50, 37), u'1', None, datetime.datetime(2013, 7, 27, 12, 9, 49), u'2013-07-29 00:00:00', u'complete', u'complete', datetime.datetime(2013, 7, 27, 7, 38, 40), 0, None, None, 0, None, None, 0) ] db = MySQLdb.connect(host="localhost", user="root", passwd="", db="inventory") cur = db.cursor() sql = """INSERT INTO daily_dispatch VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """ row = rows[0] cur.execute(sql % (row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], row[13], row[14], row[15], row[16], row[17], row[18], row[19], row[20], row[21])) db.commit() db.close() The error I get: Traceback (most recent call last): File "C:\Users\Karan\Desktop\Dropbox\Valyoo\Task 3\daily_dispatch phpmyadmin\local\insert.py", line 50, in <module> row[18], row[19], row[20], row[21])) File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 202, in execute self.errorhandler(self, exc, value) File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Card, 41420, shipping_accessories, 2013-07-27 04:12:56, 2013-07-27 11:18:04,\n ' at line 1") 1. I have no clue what's wrong. Anyone help me debug this? 2. Is there a better (visually, and performance-wise) way of inserting the tuple rather than using indexes? Answer: You are interpolating your data, leave that to the database adapter, which will handle escaping the various values as appropriate. There is also _no_ need to expand the whole list of row values: cur.execute(sql, row) You don't really have to type out all those `%s` placeholders; have Python generate them for you: sql = "INSERT INTO daily_dispatch VALUES ({})".format(', '.join(['%s' for _ in range(len(row[0]))])) Since you have more than one row, have the database loop through them and execute the same query for each row in turn: cur.executemany(sql, rows) No need to loop yourself.
How to de-activate command + Q key in pyqt application in Mac OSX? Question: My PyQt application is closed when I press (command + q) keys in Mac OSX. (i.e) My App receives close event similar to pressing (Alt +F4) keys in windows But How can I disable this type of closing event which is mac native close keyboard shortcut. Following is my sample pyqt code for which I want my qmainwindow should not receive close event. #! /usr/bin/python import sys import os from PyQt4 import QtGui class Notepad(QtGui.QMainWindow): def __init__(self): super(Notepad, self).__init__() self.initUI() def initUI(self): self.setGeometry(300,300,300,300) self.setWindowTitle('Notepad') self.show() self.raise_() #def keyPressEvent(self, keyEvent): # print(keyEvent,'hi') # print('close 0', keyEvent.InputMethod) # if keyEvent.key() != 16777249: # super().keyPressEvent(keyEvent) # else: # print(dir(keyEvent)) # return False def closeEvent(self, event): reply = QtGui.QMessageBox.question(self, 'Message', "Are you sure to quit?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: event.accept() else: event.ignore() def main(): app = QtGui.QApplication(sys.argv) notepad = Notepad() sys.exit(app.exec_()) if __name__ == '__main__': main() ??? Answer: Extend the QtGui.QApplication::events() method to receive this command + q close event and ignore it. Below is my sample code to achieve it. def main(): app = Application() notepad = Notepad() sys.exit(app.exec_()) class Application(QtGui.QApplication): def event(self, event): # Ignore command + q close app keyboard shortcut event in mac if event.type() == QtCore.QEvent.Close and event.spontaneous(): if sys.platform.startswith('darwin'): event.ignore() return False Thanks everyone
calling python script from another script Question: i'm trying to get simple python script to call another script, just in order to understand better how it's working. The 'main' code goes like this: #!/usr/bin/python import subprocess subprocess.call('kvadrat.py') and the script it calls - `kvadrat.py`: #!/usr/bin/python def kvadriranje(x): kvadrat = x * x return kvadrat print kvadriranje(5) Called script works on its own, but when called through 'main' script error occurs: Traceback (most recent call last): File "/Users/user/Desktop/Python/General Test.py", line 5, in <module> subprocess.call('kvadrat.py') File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 444, in call File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 595, in __init__ File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 1106, in _execute_child OSError: [Errno 2] No such file or directory Obviously something's wrong, but being a beginner don't see what. Answer: Have you tried: from subprocess import call call(["python","kvadrat.py"]) #if in same directory, else get abs path You should also check if your file is there: import os print os.path.exists('kvadrat.py')
Simple Python Battleship game Question: I recently started learning python and decided to try and make my first project. I'm trying to make a battleship game that randomly places two 3 block long ships on a board. But it doesn't work quite right. I made a while loop for ship #2 that's supposed to check and see if two spaces next to it are free, then build itself there. But sometimes it just slaps itself on top of where ship #1 already is. can someone help me out? **Here's the first part of the code:** from random import randint ###board: board = [] for x in range(7): board.append(["O"] * 7) def print_board(board): for row in board: print " ".join(row) ###ships' positions: #ship 1 def random_row(board): return randint(0, len(board) - 1) def random_col(board): return randint(0, len(board[0]) - 1) row_1 = random_row(board) col_1 = random_col(board) #ship 2 row_2 = random_row(board) col_2 = random_col(board) def make_it_different(r,c): while r == row_1 and c == col_1: r = random_row(board) c = random_col(board) row_2 = r col_2 = c make_it_different(row_2,col_2) ### Makes the next two blocks of the ships: def random_dir(): n = randint(1,4) if n == 1: return "up" elif n == 2: return "right" elif n == 3: return "down" elif n == 4: return "left" #ship one: while True: d = random_dir() #reset direction if d == "up": if row_1 >= 2: #building... row_1_2 = row_1 - 1 col_1_2 = col_1 row_1_3 = row_1 - 2 col_1_3 = col_1 break if d == "right": if col_1 <= len(board[0])-3: #building... row_1_2 = row_1 col_1_2 = col_1 + 1 row_1_3 = row_1 col_1_3 = col_1 + 2 break if d == "down": if row_1 <= len(board)-3: #building... row_1_2 = row_1 + 1 col_1_2 = col_1 row_1_3 = row_1 + 2 col_1_3 = col_1 break if d == "left": if col_1 >= 2: #building... row_1_2 = row_1 col_1_2 = col_1 - 1 row_1_3 = row_1 col_1_3 = col_1 - 2 break ship_1 = [(row_1,col_1),(row_1_2,col_1_2),(row_1_3,col_1_3)] **And here's where the ship 2 part is:** #ship two: while True: d = random_dir() #reset direction if d == "up": if row_2 >= 2: if (row_2 - 1,col_2) not in ship_1 and (row_2 - 2,col_2) not in ship_1: #building... row_2_2 = row_2 - 1 col_2_2 = col_2 row_2_3 = row_2 - 2 col_2_3 = col_2 break if d == "right": if col_2 <= len(board[0])-3: if (row_2 ,col_2 + 1) not in ship_1 and (row_2,col_2 + 2) not in ship_1: #building... row_2_2 = row_2 col_2_2 = col_2 + 1 row_2_3 = row_2 col_2_3 = col_2 + 2 break if d == "down": if row_2 <= len(board)-3: if (row_2 + 1 ,col_2) not in ship_1 and (row_2 + 2,col_2) not in ship_1: #building... row_2_2 = row_2 + 1 col_2_2 = col_2 row_2_3 = row_2 + 2 col_2_3 = col_2 break if d == "left": if col_2 >= 2: if (row_2 ,col_2 - 1) not in ship_1 and (row_2,col_2 - 2) not in ship_1: #building... row_2_2 = row_2 col_2_2 = col_2 - 1 row_2_3 = row_2 col_2_3 = col_2 - 2 break ###test board[row_1][col_1] = "X" board[row_1_2][col_1_2] = "X" board[row_1_3][col_1_3] = "X" board[row_2][col_2] = "Y" board[row_2_2][col_2_2] = "Y" board[row_2_3][col_2_3] = "Y" #Ship1 = X's and Ship2 = Y's print_board(board) Answer: I'd recommend allowing your placing code to run through simply and without if statements, it will be much cleaner. Then, at the end, you can check to see if any of the pieces overlap, and if they do reset. Depending on how you end up deciding to store the points that the individual ships lie in, maybe a list of tuples. You could do this the place ship method could return a list of tuples (points) def placeShip(): points = [] # put random point generation here for point in points: if point in otherShipPoints: return placeShip() # overlap detected, redo ship placement return points Put your placement code in a single function so that it can be called this way simply. Your code is starting to get messy and I recommend going to an approach like this to keep from running into spaghetti code problems. You could also give `placeShip()` a parameter for the size of ship you want to add, then this method could be your all-in-one ship placer. Just make your function look like this `placeShip(size)` and then randomly generate that many points within your grid
can python-requests fetch url directly to file handle on disk like curl? Question: curl has an option to directly save file and header data on disk: curl_setopt($curl_obj, CURLOPT_WRITEHEADER, $header_handle); curl_setopt($curl_obj, CURLOPT_FILE, $file_handle); Is there same ability in python-requests ? Answer: As far as I know, _requests_ does not provide a function that save content to a file. import requests with open('local-file', 'wb') as f: r = requests.get('url', stream=True) f.writelines(r.iter_content(1024)) See [request.Response.iter_content documentation](http://www.python- requests.org/en/latest/api.html#requests.Response.iter_content). > iter_content(chunk_size=1, decode_unicode=False) > > Iterates over the response data. When **stream=True** is set on the request, > this avoids reading the content at once into memory for large responses. The > chunk size is the number of bytes it should read into memory. This is not > necessarily the length of each item returned as decoding can take place.
compress level of python gzip module not working Question: I was trying to write data into a compressed file using the python gzip module. But the module does not seem to accept the level of compression I followed the syntax specified in the official Python documentation on [gzip](http://docs.python.org/2/library/gzip.html) Here is a sample snippet of code, please correct me if I am wrong import gzip fd = gzip.GzipFile(filename = "temp", mode = "w", compresslevel = 6) fd.write("some text") When I run the file command on the file temp I always get the output as "max compression" even though it is not in this case file temp temp: gzip compressed data, was "temp", last modified: Tue Jul 30 23:12:29 2013, max compression Answer: `some text` is too small to test. Try with big string. I tried it with a big text file, and it works as expected. import gzip import os with open('/path/to/big-file', 'rb') as f: content = f.read() for level in range(10): with gzip.GzipFile(filename='temp', mode='w', compresslevel=level) as f: f.write(content) print('level={}, size={}'.format(level, os.path.getsize('temp'))) Above code produce following output: level=0, size=56564 level=1, size=21150 level=2, size=20635 level=3, size=20291 level=4, size=19260 level=5, size=18818 level=6, size=18721 level=7, size=18713 level=8, size=18700 level=9, size=18702
Python: Kill (terminate) a process from command prompt using Python Question: I am not very familiar with the computer software terminology (my apologies). * I designed a GUI in Python that suppose to execute and/or terminate a script when an appropriate button (on the GUI) is pressed. * When I press a "Start" button (QPushButton) on the GUI, the following command executes the script _filename.dut_ in the command prompt as follows: subprocess.call ('launcher.exe localhost filename.dut', shell=True). * I want to be able to terminate the script in a similar way, i.e., to press a "Stop" button on the GUI that will write into the command prompt an appropriate command to terminate the script. I think I can find the solution in this thread: [Ending external programs with Python](http://stackoverflow.com/questions/6026791/ending-external-programs-with-python). The suggested solution is: import subprocess taskname = '...' task = 'taskkill /im ' + taskname + ' /f' subprocess.check_call(task, shell=True) * My quastion is how can I obtain the _taskname_ ? Any suggestions or alternate solution would be very appreciated. Answer: If you use `subprocess`, you don't need to call any external utilities. `subprocess.Popen` class provides `terminate` method. In order to use it, you'll need to replace `subprocess.call(...)` with `subprocess.Popen(...)`, which returns a `Popen` instance. For example, task = subprocess.Popen('launcher.exe localhost filename.dut', shell=True) # some time later task.terminate() Note that, unlike `call`, plain `Popen` doesn't wait for process to complete. Consult the manual for more details: <http://docs.python.org/2/library/subprocess.html>
Error while installing numpy in venv Question: I am getting the following error while trying to install numpy in my venv. I am running centos. which python points to the python in my venv directory (venv)bash-3.2$ pip install numpy Downloading/unpacking numpy Running setup.py egg_info for package numpy Running from numpy source directory. non-existing path in 'numpy/distutils': 'site.cfg' F2PY Version 2 blas_opt_info: blas_mkl_info: libraries mkl,vml,guide not found in ['/nrg5/nlu/data/users/indrani_gorti/venv/venv/lib', '/usr/local/lib64', '/usr/local/lib', '/usr/lib64', '/usr/lib'] NOT AVAILABLE atlas_blas_threads_info: Setting PTATLAS=ATLAS libraries ptf77blas,ptcblas,atlas not found in ['/nrg5/nlu/data/users/indrani_gorti/venv/venv/lib', '/usr/local/lib64', '/usr/local/lib', '/usr/lib64/atlas', '/usr/lib64/sse2', '/usr/lib64', '/usr/lib/sse2', '/usr/lib'] NOT AVAILABLE atlas_blas_info: libraries f77blas,cblas,atlas not found in ['/nrg5/nlu/data/users/indrani_gorti/venv/venv/lib', '/usr/local/lib64', '/usr/local/lib', '/usr/lib64/atlas', '/usr/lib64/sse2', '/usr/lib64', '/usr/lib/sse2', '/usr/lib'] NOT AVAILABLE /nrg5/nlu/data/users/indrani_gorti/venv/venv/build/numpy/numpy/distutils/system_info.py:1494: UserWarning: Atlas (http://math-atlas.sourceforge.net/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [atlas]) or by setting the ATLAS environment variable. warnings.warn(AtlasNotFoundError.__doc__) blas_info: FOUND: libraries = ['blas'] library_dirs = ['/usr/lib64'] language = f77 FOUND: libraries = ['blas'] library_dirs = ['/usr/lib64'] define_macros = [('NO_ATLAS_INFO', 1)] language = f77 lapack_opt_info: lapack_mkl_info: mkl_info: libraries mkl,vml,guide not found in ['/nrg5/nlu/data/users/indrani_gorti/venv/venv/lib', '/usr/local/lib64', '/usr/local/lib', '/usr/lib64', '/usr/lib'] NOT AVAILABLE NOT AVAILABLE atlas_threads_info: Setting PTATLAS=ATLAS libraries ptf77blas,ptcblas,atlas not found in /nrg5/nlu/data/users/indrani_gorti/venv/venv/lib libraries lapack_atlas not found in /nrg5/nlu/data/users/indrani_gorti/venv/venv/lib libraries ptf77blas,ptcblas,atlas not found in /usr/local/lib64 libraries lapack_atlas not found in /usr/local/lib64 libraries ptf77blas,ptcblas,atlas not found in /usr/local/lib libraries lapack_atlas not found in /usr/local/lib libraries ptf77blas,ptcblas,atlas not found in /usr/lib64/atlas libraries lapack_atlas not found in /usr/lib64/atlas libraries ptf77blas,ptcblas,atlas not found in /usr/lib64/sse2 libraries lapack_atlas not found in /usr/lib64/sse2 libraries ptf77blas,ptcblas,atlas not found in /usr/lib64 libraries lapack_atlas not found in /usr/lib64 libraries ptf77blas,ptcblas,atlas not found in /usr/lib/sse2 libraries lapack_atlas not found in /usr/lib/sse2 libraries ptf77blas,ptcblas,atlas not found in /usr/lib libraries lapack_atlas not found in /usr/lib numpy.distutils.system_info.atlas_threads_info NOT AVAILABLE atlas_info: libraries f77blas,cblas,atlas not found in /nrg5/nlu/data/users/indrani_gorti/venv/venv/lib libraries lapack_atlas not found in /nrg5/nlu/data/users/indrani_gorti/venv/venv/lib libraries f77blas,cblas,atlas not found in /usr/local/lib64 libraries lapack_atlas not found in /usr/local/lib64 libraries f77blas,cblas,atlas not found in /usr/local/lib libraries lapack_atlas not found in /usr/local/lib libraries f77blas,cblas,atlas not found in /usr/lib64/atlas libraries lapack_atlas not found in /usr/lib64/atlas libraries f77blas,cblas,atlas not found in /usr/lib64/sse2 libraries lapack_atlas not found in /usr/lib64/sse2 libraries f77blas,cblas,atlas not found in /usr/lib64 libraries lapack_atlas not found in /usr/lib64 libraries f77blas,cblas,atlas not found in /usr/lib/sse2 libraries lapack_atlas not found in /usr/lib/sse2 libraries f77blas,cblas,atlas not found in /usr/lib libraries lapack_atlas not found in /usr/lib numpy.distutils.system_info.atlas_info NOT AVAILABLE /nrg5/nlu/data/users/indrani_gorti/venv/venv/build/numpy/numpy/distutils/system_info.py:1408: UserWarning: Atlas (http://math-atlas.sourceforge.net/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [atlas]) or by setting the ATLAS environment variable. warnings.warn(AtlasNotFoundError.__doc__) lapack_info: FOUND: libraries = ['lapack'] library_dirs = ['/usr/lib64'] language = f77 FOUND: libraries = ['lapack', 'blas'] library_dirs = ['/usr/lib64'] define_macros = [('NO_ATLAS_INFO', 1)] language = f77 build_src building py_modules sources building library "npymath" sources customize Gnu95FCompiler Found executable /usr/bin/gfortran customize Gnu95FCompiler customize Gnu95FCompiler using config C compiler: gcc -pthread -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/nlu/users/indrani_gorti/prefix/include -fPIC -fPIC compile options: '-Inumpy/core/src/private -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -Inumpy/core/include -I/nlu/users/indrani_gorti/prefix/include/python2.7 -c' gcc: _configtest.c gcc -pthread _configtest.o -o _configtest success! removing: _configtest.c _configtest.o _configtest C compiler: gcc -pthread -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/nlu/users/indrani_gorti/prefix/include -fPIC -fPIC compile options: '-Inumpy/core/src/private -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -Inumpy/core/include -I/nlu/users/indrani_gorti/prefix/include/python2.7 -c' gcc: _configtest.c _configtest.c:1: warning: conflicting types for built-in function 'exp' gcc -pthread _configtest.o -o _configtest _configtest.o: In function `main': /nrg5/nlu/data/users/indrani_gorti/venv/venv/build/numpy/_configtest.c:6: undefined reference to `exp' collect2: ld returned 1 exit status _configtest.o: In function `main': /nrg5/nlu/data/users/indrani_gorti/venv/venv/build/numpy/_configtest.c:6: undefined reference to `exp' collect2: ld returned 1 exit status failure. removing: _configtest.c _configtest.o C compiler: gcc -pthread -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/nlu/users/indrani_gorti/prefix/include -fPIC -fPIC compile options: '-Inumpy/core/src/private -Inumpy/core/src -Inumpy/core -Inumpy/c numpy.core - nothing done with h_files = ['build/src.linux-x86_64-2.7/numpy/core/include/numpy/config.h', 'build/src.linux-x86_64-2.7/numpy/core/include/numpy/_numpyconfig.h', 'build/src.linux-x86_64-2.7/numpy/core/include/numpy/__multiarray_api.h', 'build/src.linux-x86_64-2.7/numpy/core/include/numpy/__ufunc_api.h'] building extension "numpy.core._dotblas" sources building extension "numpy.core.umath_tests" sources building extension "numpy.core.multiarray_tests" sources building extension "numpy.lib._compiled_base" sources building extension "numpy.numarray._capi" sources building extension "numpy.fft.fftpack_lite" sources building extension "numpy.linalg.lapack_lite" sources adding 'numpy/linalg/lapack_litemodule.c' to sources. adding 'numpy/linalg/python_xerbla.c' to sources. building extension "numpy.random.mtrand" sources C compiler: gcc -pthread -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/nlu/users/indrani_gorti/prefix/include -fPIC -fPIC compile options: '-Inumpy/core/src/private -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -Inumpy/core/include -I/nlu/users/indrani_gorti/prefix/include/python2.7 -c' gcc: _configtest.c gcc -pthread _configtest.o -o _configtest _configtest failure. removing: _configtest.c _configtest.o _configtest building data_files sources build_src: building npy-pkg config files Installing collected packages: numpy Running setup.py install for numpy Running from numpy source directory. non-existing path in 'numpy/distutils': 'site.cfg' F2PY Version 2 blas_opt_info: blas_mkl_info: libraries mkl,vml,guide not found in ['/nrg5/nlu/data/users/indrani_gorti/venv/venv/lib', '/usr/local/lib64', '/usr/local/lib', '/usr/lib64', '/usr/lib'] NOT AVAILABLE atlas_blas_threads_info: Setting PTATLAS=ATLAS libraries ptf77blas,ptcblas,atlas not found in ['/nrg5/nlu/data/users/indrani_gorti/venv/venv/lib', '/usr/local/lib64', '/usr/local/lib', '/usr/lib64/atlas', '/usr/lib64/sse2', '/usr/lib64', '/usr/lib/sse2', '/usr/lib'] NOT AVAILABLE atlas_blas_info: libraries f77blas,cblas,atlas not found in ['/nrg5/nlu/data/users/indrani_gorti/venv/venv/lib', '/usr/local/lib64', '/usr/local/lib', '/usr/lib64/atlas', '/usr/lib64/sse2', '/usr/lib64', '/usr/lib/sse2', '/usr/lib'] NOT AVAILABLE /nrg5/nlu/data/users/indrani_gorti/venv/venv/build/numpy/numpy/distutils/system_info.py:1494: UserWarning: Atlas (http://math-atlas.sourceforge.net/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [atlas]) or by setting the ATLAS environment variable. warnings.warn(AtlasNotFoundError.__doc__) blas_info: FOUND: libraries = ['blas'] library_dirs = ['/usr/lib64'] language = f77 FOUND: libraries = ['blas'] library_dirs = ['/usr/lib64'] define_macros = [('NO_ATLAS_INFO', 1)] language = f77 lapack_opt_info: lapack_mkl_info: mkl_info: libraries mkl,vml,guide not found in ['/nrg5/nlu/data/users/indrani_gorti/venv/venv/lib', '/usr/local/lib64', '/usr/local/lib', '/usr/lib64', '/usr/lib'] NOT AVAILABLE NOT AVAILABLE atlas_threads_info: Setting PTATLAS=ATLAS libraries ptf77blas,ptcblas,atlas not found in /nrg5/nlu/data/users/indrani_gorti/venv/venv/lib libraries lapack_atlas not found in /nrg5/nlu/data/users/indrani_gorti/venv/venv/lib libraries ptf77blas,ptcblas,atlas not found in /usr/local/lib64 libraries lapack_atlas not found in /usr/local/lib64 libraries ptf77blas,ptcblas,atlas not found in /usr/local/lib libraries lapack_atlas not found in /usr/local/lib libraries ptf77blas,ptcblas,atlas not found in /usr/lib64/atlas libraries lapack_atlas not found in /usr/lib64/atlas libraries ptf77blas,ptcblas,atlas not found in /usr/lib64/sse2 libraries lapack_atlas not found in /usr/lib64/sse2 libraries ptf77blas,ptcblas,atlas not found in /usr/lib64 libraries lapack_atlas not found in /usr/lib64 libraries ptf77blas,ptcblas,atlas not found in /usr/lib/sse2 libraries lapack_atlas not found in /usr/lib/sse2 libraries ptf77blas,ptcblas,atlas not found in /usr/lib libraries lapack_atlas not found in /usr/lib numpy.distutils.system_info.atlas_threads_info NOT AVAILABLE atlas_info: libraries f77blas,cblas,atlas not found in /nrg5/nlu/data/users/indrani_gorti/venv/venv/lib libraries lapack_atlas not found in /nrg5/nlu/data/users/indrani_gorti/venv/venv/lib libraries f77blas,cblas,atlas not found in /usr/local/lib64 libraries lapack_atlas not found in /usr/local/lib64 libraries f77blas,cblas,atlas not found in /usr/local/lib libraries lapack_atlas not found in /usr/local/lib libraries f77blas,cblas,atlas not found in /usr/lib64/atlas libraries lapack_atlas not found in /usr/lib64/atlas libraries f77blas,cblas,atlas not found in /usr/lib64/sse2 libraries lapack_atlas not found in /usr/lib64/sse2 libraries f77blas,cblas,atlas not found in /usr/lib64 libraries lapack_atlas not found in /usr/lib64 libraries f77blas,cblas,atlas not found in /usr/lib/sse2 libraries lapack_atlas not found in /usr/lib/sse2 libraries f77blas,cblas,atlas not found in /usr/lib libraries lapack_atlas not found in /usr/lib numpy.distutils.system_info.atlas_info NOT AVAILABLE /nrg5/nlu/data/users/indrani_gorti/venv/venv/build/numpy/numpy/distutils/system_info.py:1408: UserWarning: Atlas (http://math-atlas.sourceforge.net/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [atlas]) or by setting the ATLAS environment variable. warnings.warn(AtlasNotFoundError.__doc__) lapack_info: FOUND: libraries = ['lapack'] library_dirs = ['/usr/lib64'] language = f77 FOUND: libraries = ['lapack', 'blas'] library_dirs = ['/usr/lib64'] define_macros = [('NO_ATLAS_INFO', 1)] language = f77 unifing config_cc, config, build_clib, build_ext, build commands --compiler options unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options build_src building py_modules sources building library "npymath" sources customize Gnu95FCompiler Found executable /usr/bin/gfortran customize Gnu95FCompiler customize Gnu95FCompiler using config C compiler: gcc -pthread -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/nlu/users/indrani_gorti/prefix/include -fPIC -fPIC compile options: '-DNO_ATLAS_INFO=1 -Inumpy/core/include -Ibuild/src.linux-x86_64-2.7/numpy/core/include/numpy -Inumpy/core/src/private -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -Inumpy/core/include -I/nlu/users/indrani_gorti/prefix/include/python2.7 -Ibuild/src.linux-x86_64-2.7/numpy/core/src/multiarray -Ibuild/src.linux-x86_64-2.7/numpy/core/src/umath -c' gcc: numpy/linalg/lapack_litemodule.c gcc: numpy/linalg/python_xerbla.c /usr/bin/gfortran -Wall -L/nlu/users/indrani_gorti/prefix/lib build/temp.linux-x86_64-2.7/numpy/linalg/lapack_litemodule.o build/temp.linux-x86_64-2.7/numpy/linalg/python_xerbla.o -L/usr/lib64 -L/nlu/users/indrani_gorti/prefix/lib -Lbuild/temp.linux-x86_64-2.7 -llapack -lblas -lpython2.7 -lgfortran -o build/lib.linux-x86_64-2.7/numpy/linalg/lapack_lite.so /usr/lib/gcc/x86_64-redhat-linux/4.1.2/libgfortranbegin.a(fmain.o): In function `main': (.text+0xa): undefined reference to `MAIN__' collect2: ld returned 1 exit status /usr/lib/gcc/x86_64-redhat-linux/4.1.2/libgfortranbegin.a(fmain.o): In function `main': (.text+0xa): undefined reference to `MAIN__' collect2: ld returned 1 exit status error: Command "/usr/bin/gfortran -Wall -L/nlu/users/indrani_gorti/prefix/lib build/temp.linux-x86_64-2.7/numpy/linalg/lapack_litemodule.o build/temp.linux-x86_64-2.7/numpy/linalg/python_xerbla.o -L/usr/lib64 -L/nlu/users/indrani_gorti/prefix/lib -Lbuild/temp.linux-x86_64-2.7 -llapack -lblas -lpython2.7 -lgfortran -o build/lib.linux-x86_64-2.7/numpy/linalg/lapack_lite.so" failed with exit status 1 Complete output from command /nrg5/nlu/data/users/indrani_gorti/venv/venv/bin/python -c "import setuptools;__file__='/nrg5/nlu/data/users/indrani_gorti/venv/venv/build/numpy/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-o4oHZQ-record/install-record.txt --single-version-externally-managed --install-headers /nrg5/nlu/data/users/indrani_gorti/venv/venv/include/site/python2.7: Running from numpy source directory. non-existing path in 'numpy/distutils': 'site.cfg' F2PY Version 2 blas_opt_info: blas_mkl_info: libraries mkl,vml,guide not found in ['/nrg5/nlu/data/users/indrani_gorti/venv/venv/lib', '/usr/local/lib64', '/usr/local/lib', '/usr/lib64', '/usr/lib'] NOT AVAILABLE atlas_blas_threads_info: Setting PTATLAS=ATLAS libraries ptf77blas,ptcblas,atlas not found in ['/nrg5/nlu/data/users/indrani_gorti/venv/venv/lib', '/usr/local/lib64', '/usr/local/lib', '/usr/lib64/atlas', '/usr/lib64/sse2', '/usr/lib64', '/usr/lib/sse2', '/usr/lib'] NOT AVAILABLE atlas_blas_info: libraries f77blas,cblas,atlas not found in ['/nrg5/nlu/data/users/indrani_gorti/venv/venv/lib', '/usr/local/lib64', '/usr/local/lib', '/usr/lib64/atlas', '/usr/lib64/sse2', '/usr/lib64', '/usr/lib/sse2', '/usr/lib'] NOT AVAILABLE /nrg5/nlu/data/users/indrani_gorti/venv/venv/build/numpy/numpy/distutils/system_info.py:1494: UserWarning: Atlas (http://math-atlas.sourceforge.net/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [atlas]) or by setting the ATLAS environment variable. warnings.warn(AtlasNotFoundError.__doc__) blas_info: FOUND: libraries = ['blas'] library_dirs = ['/usr/lib64'] language = f77 FOUND: libraries = ['blas'] library_dirs = ['/usr/lib64'] define_macros = [('NO_ATLAS_INFO', 1)] language = f77 lapack_opt_info: lapack_mkl_info: mkl_info: libraries mkl,vml,guide not found in ['/nrg5/nlu/data/users/indrani_gorti/venv/venv/lib', '/usr/local/lib64', '/usr/local/lib', '/usr/lib64', '/usr/lib'] NOT AVAILABLE NOT AVAILABLE atlas_threads_info: Setting PTATLAS=ATLAS libraries ptf77blas,ptcblas,atlas not found in /nrg5/nlu/data/users/indrani_gorti/venv/venv/lib libraries lapack_atlas not found in /nrg5/nlu/data/users/indrani_gorti/venv/venv/lib libraries ptf77blas,ptcblas,atlas not found in /usr/local/lib64 libraries lapack_atlas not found in /usr/local/lib64 libraries ptf77blas,ptcblas,atlas not found in /usr/local/lib libraries lapack_atlas not found in /usr/local/lib libraries ptf77blas,ptcblas,atlas not found in /usr/lib64/atlas libraries lapack_atlas not found in /usr/lib64/atlas libraries ptf77blas,ptcblas,atlas not found in /usr/lib64/sse2 libraries lapack_atlas not found in /usr/lib64/sse2 libraries ptf77blas,ptcblas,atlas not found in /usr/lib64 libraries lapack_atlas not found in /usr/lib64 libraries ptf77blas,ptcblas,atlas not found in /usr/lib/sse2 libraries lapack_atlas not found in /usr/lib/sse2 libraries ptf77blas,ptcblas,atlas not found in /usr/lib libraries lapack_atlas not found in /usr/lib numpy.distutils.system_info.atlas_threads_info NOT AVAILABLE atlas_info: libraries f77blas,cblas,atlas not found in /nrg5/nlu/data/users/indrani_gorti/venv/venv/lib libraries lapack_atlas not found in /nrg5/nlu/data/users/indrani_gorti/venv/venv/lib libraries f77blas,cblas,atlas not found in /usr/local/lib64 libraries lapack_atlas not found in /usr/local/lib64 libraries f77blas,cblas,atlas not found in /usr/local/lib libraries lapack_atlas not found in /usr/local/lib libraries f77blas,cblas,atlas not found in /usr/lib64/atlas libraries lapack_atlas not found in /usr/lib64/atlas libraries f77blas,cblas,atlas not found in /usr/lib64/sse2 libraries lapack_atlas not found in /usr/lib64/sse2 libraries f77blas,cblas,atlas not found in /usr/lib64 libraries lapack_atlas not found in /usr/lib64 libraries f77blas,cblas,atlas not found in /usr/lib/sse2 libraries lapack_atlas not found in /usr/lib/sse2 libraries f77blas,cblas,atlas not found in /usr/lib libraries lapack_atlas not found in /usr/lib numpy.distutils.system_info.atlas_info NOT AVAILABLE /nrg5/nlu/data/users/indrani_gorti/venv/venv/build/numpy/numpy/distutils/system_info.py:1408: UserWarning: Atlas (http://math-atlas.sourceforge.net/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [atlas]) or by setting the ATLAS environment variable. warnings.warn(AtlasNotFoundError.__doc__) lapack_info: FOUND: libraries = ['lapack'] library_dirs = ['/usr/lib64'] language = f77 FOUND: libraries = ['lapack', 'blas'] library_dirs = ['/usr/lib64'] define_macros = [('NO_ATLAS_INFO', 1)] language = f77 running install running build running config_cc unifing config_cc, config, build_clib, build_ext, build commands --compiler options running config_fc unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options running build_src build_src building py_modules sources building library "npymath" sources customize Gnu95FCompiler Found executable /usr/bin/gfortran customize Gnu95FCompiler customize Gnu95FCompiler using config C compiler: gcc -pthread -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/nlu/users/indrani_gorti/prefix/include -fPIC -fPIC compile options: '-Inumpy/core/src/private -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -Inumpy/core/include -I/nlu/users/indrani_gorti/prefix/include/python2.7 -c' gcc: _configtest.c gcc -pthread _configtest.o -o _configtest success! removing: _configtest.c _configtest.o _configtest C compiler: gcc -pthread -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/nlu/users/indrani_gorti/prefix/include -fPIC -fPIC compile options: '-Inumpy/core/src/private -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -Inumpy/core/include -I/nlu/users/indrani_gorti/prefix/include/python2.7 -c' gcc: _configtest.c _configtest.c:1: warning: conflicting types for built-in function 'exp' gcc -pthread _configtest.o -o _configtest _configtest.o: In function `main': /nrg5/nlu/data/users/indrani_gorti/venv/venv/build/numpy/_configtest.c:6: undefined reference to `exp' collect2: ld returned 1 exit status _configtest.o: In function `main': /nrg5/nlu/data/users/indrani_gorti/venv/venv/build/numpy/_configtest.c:6: undefined reference to `exp' collect2: ld returned 1 exit status failure. removing: _configtest.c _configtest.o C compiler: gcc -pthread -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/nlu/users/indrani_gorti/prefix/include -fPIC -fPIC compile options: '-Inumpy/core/src/private -Inumpy/core/src -Inumpy/core -Inumpy/core/src/npymath -Inumpy/core/src/multiarray -Inumpy/core/src/umath -Inumpy/core/src/npysort -Inumpy/core/include -I/nlu/users/indrani_gorti/prefix/include/python2.7 -c' gcc: _configtest.c _configtest.c:1: warning: conflicting types for built-in function 'exp' gcc -pthread _configtest.o -lm -o _configtest success! removing: _configtest.c _configtest.o _configtest building library "npysort" sources building extension "numpy.core._dummy" sources adding 'build/src.linux-x86_64-2.7/numpy/core/include/numpy/config.h' to sources. adding 'build/src.linux-x86_64-2.7/numpy/core/include/numpy/_numpyconfig.h' to sources. executing numpy/core/code_generators/generate_numpy_api.py adding 'build/src.linux-x86_64-2.7/numpy/core/include/numpy/__multiarray_api.h' to sources. numpy.core - nothing done with h_files = ['build/src.linux-x86_64-2.7/numpy/core/include/numpy/config.h', 'build/src.linux-x86_64-2.7/numpy/core/include/numpy/_numpyconfig.h', 'build/src.linux-x86_64-2.7/numpy/core/include/numpy/__multiarray_api.h'] adding 'build/src.linux-x86_64-2.7/numpy/core/include/numpy/config.h' to sources. adding 'build/src.linux-x86_64-2.7/numpy/core/include/numpy/_numpyconfig.h' to sources. executing numpy/core/code_generators/generate_numpy_api.py adding 'build/src.linux-x86_64-2.7/numpy/core/include/numpy/__multiarray_api.h' to sources. executing numpy/core/code_generators/generate_ufunc_api.py adding 'build/src.linux-x86_64-2.7/numpy/core/include/numpy/__ufunc_api.h' to sources. numpy.core - nothing done with h_files = ['build/src.linux-x86_64-2.7/numpy/core/include/numpy/config.h', 'build/src.linux-x86_64-2.7/numpy/core/include/numpy/_numpyconfig.h', 'build/src.linux-x86_64-2.7/numpy/core/include/numpy/__multiarray_api.h', 'build/src.linux-x86_64-2.7/numpy/core/include/numpy/__ufunc_api.h'] building extension "numpy.core._dotblas" sources building extension "numpy.core.umath_tests" sources building extension "numpy.core.multiarray_tests" sources building extension "numpy.lib._compiled_base" sources building extension "numpy.numarray._capi" sources building extension "numpy.fft.fftpack_lite" sources /usr/bin/gfortran -Wall -L/nlu/users/indrani_gorti/prefix/lib build/temp.linux-x86_64-2.7/numpy/linalg/lapack_litemodule.o build/temp.linux-x86_64-2.7/numpy/linalg/python_xerbla.o -L/usr/lib64 -L/nlu/users/indrani_gorti/prefix/lib -Lbuild/temp.linux-x86_64-2.7 -llapack -lblas -lpython2.7 -lgfortran -o build/lib.linux-x86_64-2.7/numpy/linalg/lapack_lite.so /usr/lib/gcc/x86_64-redhat-linux/4.1.2/libgfortranbegin.a(fmain.o): In function `main': (.text+0xa): undefined reference to `MAIN__' collect2: ld returned 1 exit status /usr/lib/gcc/x86_64-redhat-linux/4.1.2/libgfortranbegin.a(fmain.o): In function `main': (.text+0xa): undefined reference to `MAIN__' collect2: ld returned 1 exit status error: Command "/usr/bin/gfortran -Wall -L/nlu/users/indrani_gorti/prefix/lib build/temp.linux-x86_64-2.7/numpy/linalg/lapack_litemodule.o build/temp.linux-x86_64-2.7/numpy/linalg/python_xerbla.o -L/usr/lib64 -L/nlu/users/indrani_gorti/prefix/lib -Lbuild/temp.linux-x86_64-2.7 -llapack -lblas -lpython2.7 -lgfortran -o build/lib.linux-x86_64-2.7/numpy/linalg/lapack_lite.so" failed with exit status 1 ---------------------------------------- Command /nrg5/nlu/data/users/indrani_gorti/venv/venv/bin/python -c "import setuptools;__file__='/nrg5/nlu/data/users/indrani_gorti/venv/venv/build/numpy/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-o4oHZQ-record/install-record.txt --single-version-externally-managed --install-headers /nrg5/nlu/data/users/indrani_gorti/venv/venv/include/site/python2.7 failed with error code 1 in /nrg5/nlu/data/users/indrani_gorti/venv/venv/build/numpy Storing complete log in /home/indrani_gorti/.pip/pip.log Answer: CFLAGS AND LDFLAGS in your bashrc file have to be unset. Then pip install numpy works.
Python; User Prompts; choose multiple files Question: I would like to have my code bring up a window where you can select multiple files within a folder and it assigns these filenames to elements of a list. Currently, I can only select a single file at a time and it assigns the filename to a single variable. from Tkinter import Tk from tkFileDialog import askopenfilename Tk().withdraw() filename = askopenfilename() Thank you. Answer: You need to use the `askopenfilenames` method instead.
How to use grid_forget to eliminate a specific ordering of buttons after they have been instantiated Question: I am building the GUI for a boardgame for my software engineering class. I am using the TKinter toolkit on Python 2.7 (windows). I am stuck right now because I cant seem to find a way to ignore/forget a certain ordering of buttons. Essentially, I am trying to create a grid of buttons that would represent my game board. And right now, I have a game board that has a total of 49 buttons on a 7x7 grid. So far this is what I have been able to do: 1. Instantiate all my button objects where columns = x and rows = y. This easily build a grid of x*y 2. I then place each button into a list (lets call this list1) 3. I want to use my list of button objects to ignore/forget/delete (for lack of a better description) certain buttons. I am thinking I can create a 2nd list (list2) of the indexes of the button objects that I want to use grid_forget on and then compare my two lists and only keep the ones that are not in list2. Unfortunately, this doesnt work out the way I want it to. Here is the code: gameboard = ttk.Labelframe(root, padding = (8,8,8,8), text = "Gameboard", relief = "sunken") #forgetButtons will not be displayed on the game board b/c they do not have a #label (they are not a: room, hallway, starting space) forgetButtons = [0,1,3,5,6,7,13,14,16,18,21,30,32,41,42,43,45,46,47,48] #this list tracks all the buttons on the gameboard myButtons=[] count = 0 for x in range(7): #build a 7x7 grid of buttons (49 buttons total) for y in range(7): btn = Button(gameboard, width=7, height=4) myButtons.append(btn) btn.grid(column=x, row=y, padx = 3, pady = 3) #do some comparison here between the two lists #to weed out the buttons found in forgetButtons #**or maybe it should not be done here?** btn.config(text="Room%d\none\ntwo\nfour\nfive" % x) Answer: You don't need `grid_forget` these widgets if you just don't create them. import itertools import Tkinter as tk root = tk.Tk() forgetButtons = [0,1,3,5,6,7,13,14,16,18,21,30,32,41,42,43,45,46,47,48] myButtons = [] for x, y in itertools.product(range(7), repeat=2): if not x*7 + y in forgetButtons: btn = tk.Button(root, width=7, height=4, text="Room%d\none\ntwo\nfour\nfive" % x) btn.grid(column=x, row=y, padx=3, pady=3) myButtons.append(btn) root.mainloop() I don't know the order to calculate the position for `forgetButtons` (usually the first index represents the row and the second one the column), but you can easily switch it.
PySide (1.1.2), cx_freeze, WinXP, Python 3.3: ImportError: DLL load failed Question: I am trying to freeze Python 3.3 code that uses PySide libs using cx_freeze and all of that on Windows XP (x86, SP2/3). The `python setup.py build` runs successfully but the executable throws an `ImportError`: > ImportError: DLL load failed: This application has failed to start because > the application configuration is incorrect. Reinstalling [...] The same builds run perfectly fine on Windows 7 x64 (SP1). The versions I am using are as follows: * Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48) [MSC v.1600 32 bit (Intel)] on win32 * cx_Freeze-4.3.1.win32-py3.3 * PySide-1.1.2.win32-py3.3 Both QT DLL libraries get copied to the build folder (`QtCore.dll`, `QtGui.dll`), the library-zip contains both .pyc equivalents in the `PySide` folder/module. This issue occurs even with the simplest test-code (~~and also if the code is run on a "live" Python installation as well~~ *): from PySide import QtCore, QtGui if __name__ == "__main__": app = QtGui.QApplication("My Application") win = QtGui.QMainWindow() win.show() app.exec_() Using a more up-to-date version of PySide might fix the problem, but since _PySide 1.2.0_ introduces a new issue with _cx-freeze_ (the file load error) I was wondering if anyone managed to freeze a PySide package on Windows XP stock successfully? Otherwise will have to wait until PySide 1.2.1 gets published and keep my hopes for that release. * See my comment: I'm not sure if this really happened during my tests for actually the same reason or for other reasons e.g. the actual module causing the issue in the frozen builds not having installed properly.. Answer: Turned out there was a simple solution to the issue: A DLL from _another_ module in use by the application was missing; copying it into the root build- out folder next to the frozen EXE easily solved the problem. The best (and probably only) approach of attack to solve these issues probably is to copy all DLLs from used modules into the build dir one by one until the frozen build doesn't throw the error anymore. I couldn't find another way as the stacktrace didn't point to a specific file that failed loading. If anyone runs into similar issues, I'd be happy to provide extra info.
how to call a python script inside another python script where both in the same directory? Question: i have two script--script1.py and script2.py. Now i want to call script1.py with in script2.py. algo will be like this-- IF condition: run script1.py #through command line ELSE : exit Answer: In `script1.py` place this: def main(): do something if __name__ == "__main__": main() In `script2.py`: import script1 if condition: script1.main()
Python and Beautiful soup - getting values and saving them in a text file Question: I have sort of a XML file contains many records of relevant info that looks like this <file> <record> <type>a</type> <number>2</number> </record> <record> <type>b</type> <number>9</number> </record> etc. I want BS to read all the XML file and to give me the results by columns : a 2 b 9 etc EDIT Thank you all for pitching in. I installed xml parser and I'm using bs4 xml mode. I don't get the error anymore however I get : a b 2 9 instead of a 2 b 9 New code : from bs4 import BeautifulSoup soup = BeautifulSoup(open('file.xml'),"xml") with open('output.txt') as f: for type1,number in (soup.findall('type'),soup.findall('number')): f.write ('%s\t%s\n' % (type1.text, number.text)) 2nd EDIT : If I add a 3rd record in the XML file, I get the following error Traceback (most recent call last): File "multixmlsript.py", line 8, in for type1,number in (soup.findAll('type'),soup.findAll('number')): ValueError: too many values to unpack Answer: from BeautifulSoup import BeautifulStoneSoup soup = BeautifulStoneSoup(open('path/to/file')) with open('/path/to/output.txt', 'w') as f: for i in range(len(soup.findAll('type'))): f.write ('%s\t%s\n' % (soup.findAll('type')[i].text, soup.findAll('number')[i].text)) You have used the `BeautifulSoup` it is for HTML. But you need to use `BeautifulStoneSoup` for xml. I hope this will be help you.
Pytests import fails after renaming project folder Question: I've been struggling for a while with renaming a project folder of a Python project. It was called Foo and I want it to rename it to Bar. Foo/ /src __init__.py x.py /test __init__.py x_test.py __init__.py became Bar/ /src __init__.py x.py /test __init__.py x_test.py __init__.py When the project folder was named Foo all my tests passed, but after renaming it to Bar my tests don't work anymore. All imports will raise an `ImportError: no module src.x`. I **can** import the module when I'm using the python console: $ python >>> import src.x When I then rename Bar back to Foo and run the test I'll get this error: import file mismatch: imported module 'test.x' has this __file__ attribute: /home/orangetux/projects/Foo/test/x_test.py which is not the same as the test file we want to collect: /home/orangetux/projects/Bar/test/x_test.py HINT: remove __pycache__ / .pyc files and/or use a unique basename for your test file modules I can fix this by removing all `__pycache__` folders. But now I'm back at the start. A folder named Foo with working test. How do I rename the project folder to Bar and keep working tests? Answer: Delete the python cache (`__pycache__`) and all "compiled" files (ie: *.pyc, *.pyo). Make sure that your **`__init.py__`** files are not referring to any folder or path.
Flask-Admin extending templates Question: I'm trying to extend my template with 'master.html' template of Flask-Admin like this: {% extends 'admin/master.html' %} {% block body %} Hello!!! {% endblock %} And I get error: File "/usr/local/Cellar/python/2.7.3/lib/python2.7/site-packages/Jinja2-2.6-py2.7.egg/jinja2/environment.py", line 894, in render return self.environment.handle_exception(exc_info, True) File "/Users/Slowpoke/Projects/Python/spider/spider/templates/form.html", line 1, in top-level template code {% extends 'admin/master.html' %} File "/usr/local/Cellar/python/2.7.3/lib/python2.7/site-packages/Flask_Admin-1.0.6-py2.7.egg/flask_admin/templates/admin/master.html", line 1, in top-level template code {% extends admin_base_template %} File "/usr/local/Cellar/python/2.7.3/lib/python2.7/site-packages/Flask-0.9-py2.7.egg/flask/templating.py", line 57, in get_source return loader.get_source(environment, local_name) File "/usr/local/Cellar/python/2.7.3/lib/python2.7/site-packages/Jinja2-2.6-py2.7.egg/jinja2/loaders.py", line 162, in get_source pieces = split_template_path(template) File "/usr/local/Cellar/python/2.7.3/lib/python2.7/site-packages/Jinja2-2.6-py2.7.egg/jinja2/loaders.py", line 29, in split_template_path for piece in template.split('/'): UndefinedError: 'admin_base_template' is undefined Here is how I'm initializing Flask-Admin: admin = Admin(app, name='Spiders') admin.add_view(AdminView(User, Session, name='Users')) And AdminView class: from flask.ext.admin.contrib.sqlamodel import ModelView from flask.ext import login class AdminView(ModelView): def is_accessible(self): return login.current_user.is_authenticated() Answer: I ran into the same issue trying to extend the Flask-Admin templates. Changing `return render_template('path_to_template')` to `return self.render('path_to_template')` resolved the issue.
Typecast from Enthoughts traits to python native objects Question: This seems to be a trivial task, still I do not find a solution. When using the API of enthought.traits and working with their data types (e.g. an integer Int), how can I typecast these values into native python objects within the `HasTraits` class. For example: from traits.api import HasTraits, Int, List class TraitsClass(HasTraits): test = Int(10) channel = List(range(0,test)) # this fails as range expects integers I tried the following within the class, both yielding errors test_int = int(test) test_int = test.get_value() Someone having a quick hint for me? Thanks a lot. Answer: You can access the default value you gave to the trait by `test.default_value`. However, I suspect that is not what you want to do... In a normal use pattern, a trait needs to be used in a `HasTraits` class. When the class is instantiated, traits are transformed in regular Python object, with some machinery to listen to changes to the trait, etc. For example: In [14]: from traits.api import HasTraits, Int In [15]: class Test(HasTraits): ....: x = Int(10) ....: In [16]: test = Test() In [17]: test.x Out[17]: 10 In [18]: type(test.x) Out[18]: int
How to execute raw SQL in SQLAlchemy-flask app Question: How do you execute raw SQL in SQLAlchemy? I have a python web app that runs on flask and interfaces to the database through SQLAlchemy. I need a way to run the raw SQL. The query involves multiple table joins along with Inline views. I've tried: connection = db.session.connection() connection.execute( <sql here> ) But I keep getting gateway errors. Answer: Have you tried: result = db.engine.execute("<sql here>") or: from sqlalchemy import text sql = text('select name from penguins') result = db.engine.execute(sql) names = [] for row in result: names.append(row[0]) print names
RegExp Look for part but exclude If Question: Right so RegExp is fairly new to me and its still puzzling me. Anyway I managed to look for almost all the names I want to but now I have to look for names that have specific part of world in it but exclude if there is another one next to it. So basically Looks for `"Cat"` however if there is `"Dog"` then exclude this string so a: CatBlablablaDog = exclude blablaCatBlabla = include Dog_blabla_Cat = exclude Atm I'm using this to look for my names `'*Cat*'` I guess I could also use `/*.Cat/` or something similar to that(I cant remember exact symbols I have it somewhere written) So what do I have to add to exclude the Dog objects? (I code in Python) If I cant do it this way maybe I can loop through objects and look for other names than Dog. Then iterate through the new non dog names for Cat names? Which mean what do I type to not look for Dog name? :) Thanks, bye. Answer: Use negative look-ahead: ^(?!.*dog).*cat.*$ It will first test that there is no `dog` further in the string. If negative look-ahead succeeds, then it goes on to match the string containing `cat`. You might want to enable ignore case in it using `(?i)` flag. In python, you can also use `re.IGNORECASE`: >>> import re >>> ignorecase = re.compile(r'(?i)(?!.*dog).*cat.*') >>> print ignorecase.match("CatBlablablaDog") None >>> >>> print ignorecase.match("blablaCatBlabla") <_sre.SRE_Match object at 0x956b090> >>> >>> print ignorecase.match("Dog_blabla_Cat") None
Python: Write dictionary to text file with ordered columns Question: I have a dictionary D where: D = {'foo':{'meow':1.23,'mix':2.34}, 'bar':{'meow':4.56, 'mix':None}, 'baz':{'meow':None,'mix':None}} I wrote this code to write it to a text file: def dict2txt(D, writefile, column1='-', delim='\t', width=20, order=['mix','meow']): import csv with open( writefile, 'w' ) as f: writer, w = csv.writer(f, delimiter=delim), [] head = ['{!s:{}}'.format(column1,width)] for i in D[D.keys()[0]].keys(): head.append('{!s:{}}'.format(i,width)) writer.writerow(head) for i in D.keys(): row = ['{!s:{}}'.format(i,width)] for k in order: row.append('{!s:{}}'.format(D[i][k],width)) writer.writerow(row) But the output ignores `order = ['mix','meow']` and writes the file like: - meow mix bar None 4.56 foo 2.34 1.23456 baz None None How do I get it to write: - mix meow bar 4.56 None foo 1.23456 2.34 baz None None Thanks! Update: Thanks to @SukritKalra in the comments below for pointing out that the code works fine. I just wasn't reordering the column headers! The line `for i in D[D.keys()[0]].keys(): head.append('{!s:{}}'.format(i,width))` should read `for i in order: head.append('{!s:{}}'.format(i,width))`. Thanks folks! Answer: Take advantage of your "order" variable to drive some generators: def dict2txt(D, writefile, column1='-', delim='\t', width=20, order=['mix','meow']): import csv # simplify formatting for clarity fmt = lambda s: '{!s:{}}'.format(s, width) with open(writefile, 'w') as f: writer = csv.writer(f, delimiter=delim) writer.writerow([fmt(column1)] + [fmt(s) for s in order]) for i in D.keys(): writer.writerow([fmt(i)] + [fmt(D[i][k]) for k in order]) The rows are still unordered. So you might want something like: "for i in sorted(D.keys()):"
Porting Django Project to 1&1 Shared Hosting Web-server Question: As a little background, I've been developing a django application for a 1&1 shared hosting website. When I tried to port the app to the web, I followed the tutorial from here: <http://robhogg.me.uk/post/2>. The servers have Python 2.6, and I installed django and flup through SSH. Here is my .fsgi file... #!/usr/bin/python import sys, os basepath = '/home/path/' # This isn't my actual homepath sys.path.insert(0, basepath + '/.local/lib') sys.path.insert(0, basepath + '/mysite') os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' from django.core.servers.fastcgi import runfastcgi runfastcgi(method='threaded', daemonize='false') ...and here is my .htaccess file... AddHandler fcgid-script .fcgi RewriteEngine on RewriteCond %{REQUEST_FILENAME} !(cgi-bin/mysite.fcgi) RewriteRule ^(.*)$ cgi-bin/mysite.fcgi/$1 [QSA,L] I also already gave the .fcgi script 755 permissions. When I run the .fcgi script, the homepage HTML prints on the console (which according to many sites means the script is good). But when I go to my website's domain, I was getting just an Index.html page that was sitting in my home directory. So I moved all the html files from the home directory, and tried again. But this time I get an error: Forbidden You don't have permission to access / on this server. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. I tried one more thing, and that was in the .htaccess file, changing AddHandler fcgid-script .fcgi to AddHandler fastcgi-script .fcgi After searching everywhere, I couldn't find a solution, so I followed the directions on this site: <https://help.asmallorange.com/index.php?/Knowledgebase/Article/View/140> Even though it was a different host, it was the same concept with similar steps. I followed all the steps, creating a new project and everything, and in the end, had the same issue. I've been through a ton of posts like this one, but none have had a solution that worked yet. Maybe this is a 1&1 specific issue, but I would really appreciate the help if anyone has any suggestions. Answer: I got the same error as you got. But after I moved the .htaccess file to the django project folder, it works.
Python UDP sendto() Ignoring Exception Block and Crashing Question: I have been trying to get a basic chat application working for months in python 2.7 (Using Geany IDE), and finally got a basic application working using UDP. I can connect and broadcast communications, but if a client connects and then closes later, the server crashes the next time it tries to broadcast a message to all of the clients. The issue is that it crashes without returning an error message or a traceback so I can't tell exactly what's happening. Here is the code (it will only work on windows due to the `getch()` code in the client). Server: from socket import * s = socket(AF_INET,SOCK_DGRAM) s.bind(("25.150.175.48",65437)) maxsize = 4096 listeners = [] while True: data, addr = s.recvfrom(maxsize) if addr not in listeners: listeners.append(addr) #print addr[1] print "new client added from %s on port %i" % (addr[0],addr[1]) for l in listeners: try: s.sendto(data,l) except: listeners.remove(l) Client: from socket import * import select import msvcrt s = socket(AF_INET,SOCK_DGRAM) s.bind(("25.150.175.48",65438))#change port to 65439 for the second client maxsize = 4096 waitseconds = 0.001 server = ("25.150.175.48",65437) s.sendto(raw_input(">"),server) while True: ready = select.select([s], [], [], waitseconds) if ready[0]: data = s.recv(maxsize) print data else: if msvcrt.kbhit(): char = msvcrt.getch() if char == "\r": s.sendto(raw_input(">"),server) My theory is that if I can have the server recognize when a person closes the client, I can remove the client address from the list of listeners and it will work fine. Unfortunately, it's not working correctly, and I don't know how to have the server send out a test packet of some sort that I can use to verify connection. All the examples I've read on the internet seem to just verify that the port exists. If anyone has any idea on how to handle this, I would greatly appreciate the help. **EDIT:** After tooling around a bit I finally managed to receive a traceback by running the server program in IDLE. the traceback is as follows: Traceback (most recent call last): File "G:\Python\Miscellaneous\Examples\UDP Chat Server & Client\UDP server.py", line 7, in <module> data, addr = s.recvfrom(maxsize) error: [Errno 10054] An existing connection was forcibly closed by the remote host I need some help handling this, as my try/except statement seems to fail to catch this when I run it (Which I'm seriously concerned about; python bug?). After returning this traceback the program quits. Any suggestions? Answer: You won't get any traceback with your try\except block. Unless you really know what you're doing you shouldn't ignore errors like that. try: s.sendto(data,l) except Exception as e: print(e) listeners.remove(l) As for the crash it's hard to say. UDP is not connection oriented, so the client being running or not shouldn't crash your server, or even stop it from sending the packages. The only way you can check if a client is online, using UDP exclusively, is by sending a package and removing it from the list if it doesn't respond in a period of time.
Python and Beautiful soup, pick up All elements Question: I'm getting a text article from one website with help of `python` and `BeatifulSoup`. Now I have strange problem... I just wana print out the text inside multiple `p` tags which are located in div with class `dr_article`. Now the with code looking like this: from bs4 import BeautifulSoup def getArticleText(webtext): soup = BeautifulSoup(webtext) divTag = soup.find_all("div", {"class":"dr_article"}) for tag in divTag: pData = tag.find_all("p").text print pData I'm getting following error: Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> execfile("word_rank/main.py") File "word_rank/main.py", line 7, in <module> articletext.getArticleText(webtext) File "word_rank\articletext.py", line 7, in getArticleText pData = tag.find_all("p").text AttributeError: 'list' object has no attribute 'text' But when I choose just the first element with `[0]` before `.text` I'm not getting the error and it works as supposed to. It gets first element text. To be precise I modify my code and it looks like this: from bs4 import BeautifulSoup def getArticleText(webtext): soup = BeautifulSoup(webtext) divTag = soup.find_all("div", {"class":"dr_article"}) for tag in divTag: pData = tag.find_all("p")[0].text print pData My question is how can I get text from all element at once? What to modify so I would not get text from only one element but from all? Answer: You are getting all element, so the function returns the list. Try to go through it: from bs4 import BeautifulSoup def getArticleText(webtext): soup = BeautifulSoup(webtext) divTag = soup.find_all("div", {"class":"dr_article"}) for tag in divTag: for element in tag.find_all("p"): pData = element.text print pData Or you can select each element separately: tag.find_all("p")[0].text tag.find_all("p")[1].text tag.find_all("p")[..].text tag.find_all("p")[N - 1].text tag.find_all("p")[N].text
Randomly Shuffle Keys and Values in Python DIctionary Question: Is there a way to randomly shuffle what keys correspond to what values? I have found random.sample but I was wondering if there was a more pythonic/faster way of doing this. Example: `a = {"one":1,"two":2,"three":3}` Shuffled: `a_shuffled = {"one":2,"two":3,"three":1}` Answer: In [47]: import random In [48]: keys = a.keys() In [49]: values = a.values() In [50]: random.shuffle(values) In [51]: a_shuffled = dict(zip(keys, values)) In [52]: a_shuffled Out[52]: {'one': 2, 'three': 1, 'two': 3} Or, more pithy would be: In [56]: dict(zip(a.keys(), random.sample(a.values(), len(a)))) Out[56]: {'one': 3, 'three': 2, 'two': 1} (but I suppose that is the solution you already came up with.) * * * Note that although using `random.sample` is pithier, using `random.shuffle` is a bit faster: import random import string def using_shuffle(a): keys = a.keys() values = a.values() random.shuffle(values) return dict(zip(keys, values)) def using_sample(a): return dict(zip(a.keys(), random.sample(a.values(), len(a)))) N = 10000 keys = [''.join(random.choice(string.letters) for j in range(4)) for i in xrange(N)] a = dict(zip(keys, range(N))) In [71]: %timeit using_shuffle(a) 100 loops, best of 3: 5.14 ms per loop In [72]: %timeit using_sample(a) 100 loops, best of 3: 5.78 ms per loop
python ast module fails in pydev, succeeds in cmdline python Question: This is weird. I run this program in PyDev import ast import sys if __name__ == '__main__': print sys.version src = ''' print 3*4+5**2 ''' print dir(ast) n = ast.parse(src) print n and it outputs: 2.7.5 |Anaconda 1.6.0 (64-bit)| (default, May 31 2013, 10:45:37) [MSC v.1500 64 bit (AMD64)] ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__'] Traceback (most recent call last): File ["C:\research\ast\ast\test1.py", line 16, in <module> n = ast.parse(src) AttributeError: 'module' object has no attribute 'parse' but when I run it in cmdline it prints this: C:\research\ast\ast>python test1.py 2.7.5 |Anaconda 1.6.0 (64-bit)| (default, May 31 2013, 10:45:37) [MSC v.1500 64 bit (AMD64)] ['AST', 'Add', 'And', 'Assert', 'Assign', 'Attribute', 'AugAssign', 'AugLoad', ' AugStore', 'BinOp', 'BitAnd', 'BitOr', 'BitXor', 'BoolOp', 'Break', 'Call', 'Cla ssDef', 'Compare', 'Continue', 'Del', 'Delete', 'Dict', 'DictComp', 'Div', 'Elli psis', 'Eq', 'ExceptHandler', 'Exec', 'Expr', 'Expression', 'ExtSlice', 'FloorDi v', 'For', 'FunctionDef', 'GeneratorExp', 'Global', 'Gt', 'GtE', 'If', 'IfExp', 'Import', 'ImportFrom', 'In', 'Index', 'Interactive', 'Invert', 'Is', 'IsNot', ' LShift', 'Lambda', 'List', 'ListComp', 'Load', 'Lt', 'LtE', 'Mod', 'Module', 'Mu lt', 'Name', 'NodeTransformer', 'NodeVisitor', 'Not', 'NotEq', 'NotIn', 'Num', ' Or', 'Param', 'Pass', 'Pow', 'Print', 'PyCF_ONLY_AST', 'RShift', 'Raise', 'Repr' , 'Return', 'Set', 'SetComp', 'Slice', 'Store', 'Str', 'Sub', 'Subscript', 'Suit e', 'TryExcept', 'TryFinally', 'Tuple', 'UAdd', 'USub', 'UnaryOp', 'While', 'Wit h', 'Yield', '__builtins__', '__doc__', '__file__', '__name__', '__package__', ' __version__', 'alias', 'arguments', 'boolop', 'cmpop', 'comprehension', 'copy_lo cation', 'dump', 'excepthandler', 'expr', 'expr_context', 'fix_missing_locations ', 'get_docstring', 'increment_lineno', 'iter_child_nodes', 'iter_fields', 'keyw ord', 'literal_eval', 'mod', 'operator', 'parse', 'slice', 'stmt', 'unaryop', 'w alk'] <_ast.Module object at 0x0000000002A99EB8> What could be going wrong? Answer: It seems the `ast` you have imported in PyDev is not the ast module in the standard library, but a package. I guess: > There is a `__init__.py` file in the same directory as your test1.py. > You selected "Add project directory to the PYTHONPATH" during the project > creation. These two combined, results in that error. The ast module in the standard library is shadowed by this `ast` package. In cmdline python, this `ast` package is not in the search path, thus the ast module is imported. If you change test1.py to import ast if __name__ == '__main__': print ast.__file__ I guess the output in PyDev would be C:\research\ast\ast\__init__.pyc
Python tkinter: Add button to menu bar Question: I am trying to add a button to the far right of the menubar in my program. But it isn't working for me. When I connect it to 'root' it appears below it; when I attach it to 'menubar' or 'filemenu' it doesn't show up at all. Here is my code: from tkinter import * root = Tk() menubar = Menu(root) # set up button btn1 = Button(root, text='x') btn1.pack(side='right', anchor='n', padx=0, pady=0) filemenu = Menu(menubar,tearoff=0) # add commands to menu filemenu.add_command(label="New File") filemenu.add_command(label="Open") filemenu.add_command(label="Save") menubar.add_cascade(label="File", menu=filemenu) root.config(menu=menubar) root.mainloop() Answer: You cannot do what you want. The menubar is a special, native control that doesn't support the ability to add random buttons to it. You can use `add_command` on the menubar itself rather than a submenu, but I think your users would be surprised at this. People generally expect to get a menu when they click on something on the menubar.
Calling DLL function in Python Question: I am having trouble understanding on how to call dll functions from an existing dll in Python. OTAClient = cdll.LoadLibrary("C:\PATH\OTAClient.dll") connect = OTAClientDLL.TDConnection() * * * exceptions.AttributeError: function 'TDConnection' not found I read something the name being mangled by the compiler. Any suggestions? Answer: The DLL was actually a COM DLL. comtypes is needed to use this type of DLL instead of ctypes. Make sure to [download comtypes](http://sourceforge.net/projects/comtypes/files/) from comtypes.client import CreateObject OTAClientDLL = comtypes.client.GetModule("C:\PATH\OTAClient.dll")
Python mysql: how do loop through table and regex-replacing field? Question: I am trying to iterate a table, fetch the rows in which a field has a pattern, then update the same row with a match group. The following code runs without error, the two `print` lines before `update` clause output correct values. I have followed similar answers to come up the `update` clause, the logic seems right to me. However the code does not work, i.e., no rows updated. Where did I do wrong? Thanks, # -*- coding: utf-8 -*- import re import MySQLdb pattern = re.compile('@(.*)@.*$') conn = MySQLdb.connect( host='localhost', user='root', passwd='password', db='j314', charset='utf8') cursor = conn.cursor() cursor.execute( """select `id`, `created_by_alias` from w0z9v_content where `catid` = 13 AND `created_by_alias` regexp "^@.*@.*$" limit 400""") aliases = cursor.fetchall() for alias in aliases: newalias = pattern.match(alias[1]) if newalias.group(1) is not None: # print alias[0] # print newalias.group(1) cursor.execute(""" update w0z9v_content set created_by_alias = %s where id = %s""", (newalias.group(1), alias[0])) conn.close Answer: [`autocommit`](http://dev.mysql.com/doc/refman/5.6/en/server-system- variables.html#sysvar_autocommit) is probably globally disabled on the server. Execute either `COMMIT` after your updates, or `SET autocommit=1` at the beginning of the session. <http://dev.mysql.com/doc/refman/5.0/en/commit.html> Also, you're not actually closing the connection, you forgot to _call_ close: `conn.close()`
Having problems reproducing Matlab results in Python for a coupled system of ODE's Question: I just started to use Python and have a bunch of code I want to transfer over from Matlab. I started with a simple coupled diff eq and can't seem to figure out what I'm doing wrong. It appears that the second diff eq is almost giving me the appropriate results but the first equation is just remaining at its initial condition for the entire time span. The first image is the Python result and the second is the correct result from Matlab. 1) ![](http://i.imgur.com/VSFpCT3.png) 2) ![](http://i.imgur.com/w7sfWko.png) from scipy.integrate import odeint from pylab import * minfH_ab = lambda v: 1/(1 + exp((v+70)/6)) taumH_ab = lambda v: 272 + 1499/(1 + exp(-(v+42.2)/8.73)) Csn = 9 I_ab_sn = 0 gL_ab_sn = 0.045 El_ab_sn = -50 gH_ab = 0.054 Eh_ab = -20 def dy_dt(y, t): dy1 = (1/Csn)*(I_ab_sn -((gH_ab*y[1]*(y[0]-Eh_ab))+(gL_ab_sn*(y[0]-El_ab_sn)))) dy2 = (minfH_ab(y[0])-y[1])/taumH_ab(y[0]) return [dy1, dy2] t = linspace(0,1000,10000) y_init = [-50, .0004] sol = odeint(dy_dt, y_init, t) S0 = sol[:, 0] S1 = sol[:, 1] figure() plot(t, S0) xlabel('time') ylabel('voltage') title('H & L Current') Answer: Since this turned out to be the answer: # Beware integer arithmetic. If you're porting from a language that does not do this by default, you may be surprised when x=50 y=6 z=5 x*y/z == 60 x*(y/z) == 50 x/y*z == 40 x*z/y == 41 And so on. Try changing all constants to doubles (`5` -> `5.0`, etc.), and see if that helps. EDIT: @BenDundee pointed out that python will be switching syntax to `/` meaning "real division", and integer division being specified with the `//` operator. You can switch to that behaviour now, with the line `from __future__ import division`, which should also resolve the problem.
Flask-Admin Blueprint creation during Testing Question: I'm having trouble with the creation of blueprints by Flask-Admin when I'm testing my app. This is my View class (using SQLAlchemy) ## # All views that only admins are allowed to see should inherit from this class. # class AuthView(ModelView): def is_accessible(self): return current_user.is_admin() class UserView(AuthView): column_list = ('name', 'email', 'role_code') This is how I initialize the views: # flask-admin admin.add_view(UserView(User, db.session)) admin.init_app(app) However, when I try to run more then one test (the fault always occurs on the second test and all the other tests that follow), I always get following error message: ====================================================================== ERROR: test_send_email (tests.test_views.TestUser) ---------------------------------------------------------------------- Traceback (most recent call last): File "/lib/python2.7/site-packages/nose/case.py", line 133, in run self.runTest(result) File "/lib/python2.7/site-packages/nose/case.py", line 151, in runTest test(result) File "/lib/python2.7/site-packages/flask_testing.py", line 72, in __call__ self._pre_setup() File "/lib/python2.7/site-packages/flask_testing.py", line 80, in _pre_setup self.app = self.create_app() File "/tests/test_init.py", line 27, in create_app app = create_app(TestConfig) File "/fbone/app.py", line 41, in create_app configure_extensions(app) File "/fbone/app.py", line 98, in configure_extensions admin.add_view(UserView(User, db.session)) File "/lib/python2.7/site-packages/flask_admin/base.py", line 484, in add_view self.app.register_blueprint(view.create_blueprint(self)) File "/lib/python2.7/site-packages/flask/app.py", line 62, in wrapper_func return f(self, *args, **kwargs) File "/lib/python2.7/site-packages/flask/app.py", line 885, in register_blueprint (blueprint, self.blueprints[blueprint.name], blueprint.name) AssertionError: A blueprint's name collision occurred between <flask.blueprints.Blueprint object at 0x110576910> and <flask.blueprints.Blueprint object at 0x1103bd3d0>. Both share the same name "userview". Blueprints that are created on the fly need unique names. The strange thing is that this only happens on the second test and never when I just run the app. When I debugged the tests, the first time it did exactly what I expected and added the blueprint to the app after the init_app(app). The second time however the process immediately stopped when reaching the add_view step (which I think is strange because the blueprints get registered in the init_app(app) call?) Answer: The same thing happened to me while using Flask-Admin and testing with pytest. I was able to fix it without creating teardown functions for my tests by moving the creation of the admin instance into the app factory. Before: # extensions.py from flask.ext.admin import Admin admin = Admin() # __init__.py from .extensions import admin def create_app(): app = Flask('flask_app') admin.add_view(sqla.ModelView(models.User, db.session)) admin.init_app(app) return app After: # __init__.py from flask.ext.admin import Admin def create_app(): app = Flask('flask_app') admin = Admin() admin.add_view(sqla.ModelView(models.User, db.session)) admin.init_app(app) return app Because pytest runs the app factory each time it no longer tries to register multiple views on a global admin instance. This isn't consistent with typical Flask extension usage, but it works and it'll keep your app factory from stumbling over Flask-Admin views.
Organize data sent between client-server Question: Pardon me if this has been addressed before, but how do I organize data exchanged between client and server in python application (sockets)? Let's say I have some elements I have to send - strings, tuples, dicts: "hello world", (1, 2, 3), {"k": "v"} What I currently do is I simply convert everything to string - call `repr()` before sending and `eval()` after receiving. This obviously seem a bit redundant. How should I send these chunks of data? Is there a convention? Preferred format? How do I compress it? Answer: JSON is what you're looking for. If you have an object and you import the JSON functions: from json import dumps, loads you can use `dumps(obj)` to encode into JSON and `loads(str)` to convert a JSON string back to an object. For example: dumps([[1,2,3],{"a":"b", "c":"d"}]) yields `'[[1, 2, 3], {"a": "b", "c": "d"}]'` and loads('[[1, 2, 3], {"a": "b", "c": "d"}]') yields `[[1, 2, 3], {u'a': u'b', u'c': u'd'}]`.
Function declaration in Python Question: I am using Theano in Python. I have the following code: outtmp = trainfunc(some_parameters) I cannot find any declaration of the `trainfunc` function, while I can only find a piece of code before the previous one as: # Function compilation trainfunc = TrainFn1Member(some_other_parameters) I can find the declaration of `TrainFn1Member` but the two functions (`trainfunc` and `TrainFn1Member`) do not have the same signature (input parameters). What does this mean, and is the second code segment the declaration of `trainfunc`? Answer: Mostly when name starts with uppercase letter then it is class name (unless it is completely upper cased, then it mostly means constant). There is no `new` operator in Python so this naming pattern is pretty important to distinguish functions from classes (anyway it is general pattern). I don't know Theano, but I suppose that `TrainFn1Member` is a class that implements `__call__` method, so you can call it's instance like a function. Search for `__call__` in `TrainFn1Member` class definition. * * * UPDATE: According to your comment, `TrainFn1Member` is a function (what is pretty strange according to what I said above and what is not my idea ;)). In this case it has to return some `callable` what means that it returns one of 3 things (I hope I have not missed anything): 1. function (`def` or `lambda`) 2. instance of class that implements `__call__` 3. method of some object (function bound to some class instance) As I don't know `Theano` at all, I can only suggest to search deeper being aware of those above.. (and welcome to Hogwarts ;))
having multiples clasess in a module in a package in Python? Question: I'm having trouble understanding packages in Python. In particular, is it possible to have multiple classes in a module in a package in Python. For example: Kitchen/ Top-level package __init__.py Initialize the package kitchen Fridge.py module Fridge.py Food This is a class in module Fridge Temperature This is another class in module Fridge Recipe.py BeefStake This is a class in module Recipe.py In the `__init__.py`, the code will be: from Fridge import Food, Temperature from Recipe import BeefStake __all__ = ['Fridge', 'Recipe'] Then I would create an instance of the Temperature class by from Kitchen import * f = Food() T = Temperature() I tried this, and only making `f = Food()` works. The other one showed up an error, something like `NameError: name 'Temperature' is not defined` If anyone knows if it is possible to have 2 classes like this in a module in a package in Python. If so, what could be the problem in this approach? Answer: The code you showed us won't work for _either_ `Food` or `Temperature`. You explicitly put this in `Kitchen`: __all__ = ['Fridge', 'Recipe'] This means that, even though you've imported `Food` and `Temperature` into `Kitchen`, you don't re-export them. So, `f = Food()` will raise a `NameError`. If you change this to, say: __all__ = ['Food', 'Temperature'] Now everything works fine. My guess is that in your real code, you made one of two mistakes: * Forgot to include `Temperature` in `__all__`, just as you did with both `Food` and `Temperature` here, or * Had a typo somewhere, e.g., `t = temperature()` with a lowercase `t`. Normally I'd suspect that the first is more likely… but given that you're inconsistent with capitalization, and misspelled `BeefSteak`, I'd check the second here.
Parsing an HTML table to a list in python Question: So I have a few strings that I am pulling from IMDb's award pages: <table><tr><td><big>Academy Awards, USA</big> </td> </tr> <tr> <th>Year</th><th>Result</th><th>Award</th><th>Category/Recipient(s)</th> </tr> <tr> <td rowspan="11" align="center" valign="middle"> 1978 </td> <td rowspan="7" align="center" valign="middle"><b>Won</b></td> <td rowspan="6" align="center" valign="middle">Oscar</td> <td valign="top"> Best Art Direction-Set Decoration John Barry Norman Reynolds Leslie Dilley Roger Christian <small> </small> </td> </tr> <tr> <td valign="top"> Best Costume Design John Mollo <small> </small> </td> </tr> <tr> <td valign="top"> Best Effects, Visual Effects John Stears John Dykstra Richard Edlund Grant McCune Robert Blalack <small> </small> </td> </tr> <tr> <td valign="top"> Best Film Editing Paul Hirsch Marcia Lucas Richard Chew <small> </small> </td> </tr> <tr> <td valign="top"> Best Music, Original Score John Williams <small> </small> </td> </tr> <tr> <td valign="top"> Best Sound Don MacDougall Ray West Bob Minkler Derek Ball <small> Derek Ball was not present at the awards ceremony. </small> </td> </tr> <tr> <td rowspan="1" align="center" valign="middle">Special Achievement Award</td> <td valign="top"> Ben Burtt (as Benjamin Burtt Jr.) <small> For sound effects. (For the creation of the alien, creature and robot voices.) </small> </td> </tr> <tr> <td rowspan="4" align="center" valign="middle"><b>Nominated</b></td> <td rowspan="4" align="center" valign="middle">Oscar</td> <td valign="top"> Best Actor in a Supporting Role Alec Guinness <small> </small> </td> </tr> <tr> <td valign="top"> Best Director George Lucas <small> </small> </td> </tr> <tr> <td valign="top"> Best Picture Gary Kurtz <small> </small> </td> </tr> <tr> <td valign="top"> Best Writing, Screenplay Written Directly for the Screen George Lucas <small> </small> </td> </tr> <tr> </tr></table> I want to pull the headers (Year, Result, Award, and Category/Recipient) to a list and then each of the columns to their own list, respectively. For example (using the Academy Award table)(Website for reference: <http://www.imdb.com/title/tt0076759/awards>): Columns = {"Year", "Result", "Award", "Category/Recipient"} Years = {"1978", "1978", "1978", "1978", "1978", "1978", "1978"} Results = {"Oscar", "Oscar", "Oscar", "Oscar", "Oscar", "Oscar", "Special Achievement Award"} Categories/Recipients = {"Best Art Direction-Set Decoration (John Barry, Norman Reynolds, Leslie Dilley, Roger Christian)", "Best Costume Design (John Mollo)", "Best Effects, Visual Effects (John Stears, John Dykstra, Richard Edlund, Grant McCune, Robert Blalack)", Best Film Editing (Paul Hirsch, Marcia Lucas, Richard Chew)", "Best Music, Original Score (John Williams)", "Best Sound (Don MacDougall, Ray West, Bob Minkler, Derek Ball)", "(Ben Burtt (as Benjamin Burtt Jr.))"} As you can see, I removed the unnecessary spacing from the table and put all the names in parenthesis. There are tags around all of the names, but I removed them (they can be kept in if it helps putting them in parenthesis easier). I also have the same number of items in each of the lists except for the Columns list. Here is my current script so you know how I manipulate it already: import shutil import urllib2 import re from lxml import etree award_usock = urllib2.urlopen('http://www.imdb.com/title/tt0076759' + '/awards') award_html = award_usock.read() award_usock.close() if "<big>" in award_html: for a_show in re.finditer('<big>',award_html): award_show_full_end = award_html.find('<td colspan="4">&nbsp;</td>',a_show.end()) award_show_full = award_html[a_show.start():award_show_full_end] award_show_full = award_show_full.replace('\n','') # award_show_full = award_show_full.replace(' ','') award_show_full = award_show_full.replace('</a>','') award_show_full = award_show_full.replace('<br />','') award_show_full = re.sub('<a href="/name/[^>]*>', '', award_show_full) award_show_full = re.sub('<a href="/title/[^>]*>', '', award_show_full) for a_s_title in re.finditer('<a href="',award_show_full): award_title_loc = award_show_full.find('<a href="') award_title_end = award_show_full.find('">',award_title_loc+10) award_title_del = award_show_full[award_title_loc:award_title_end+2] award_show_full = award_show_full.replace(award_title_del,'') award_show_full = '<table><tr><td>' + award_show_full.replace('<br>','') + '</tr></table>' award_show_loc = award_html.find('>',a_show.end()) award_show_end = award_html.find('</a></big>',a_show.end()) award_show = award_html[award_show_loc+1:award_show_end] award_show_table = etree.XML(award_show_full) award_show_rows = iter(award_show_table) award_show_headers = [award_show_col.text for award_show_col in next(award_show_rows)] for award_show_row in award_show_rows: award_show_values = [award_show_col.text for award_show_col in award_show_row] print dict(zip(award_show_headers,award_show_values)) But this produces a result: {None: 'Year'} {None: ' 1978 '} {None: ' Best Costume Design John Mollo '} {None: ' Best Effects, Visual Effects John Stears John Dykstra Richard Edlund Grant McCune Robert Blalack '} {None: ' Best Film Editing Paul Hirsch Marcia Lucas Richard Chew '} {None: ' Best Music, Original Score John Williams '} {None: ' Best Sound Don MacDougall Ray West Bob Minkler Derek Ball '} {None: 'Special Achievement Award'} {None: None} {None: ' Best Director George Lucas '} {None: ' Best Picture Gary Kurtz '} {None: ' Best Writing, Screenplay Written Directly for the Screen George Lucas '} {} Answer: It's [not a good idea](http://stackoverflow.com/questions/1732348/regex-match- open-tags-except-xhtml-self-contained-tags) to parse HTML using regular expressions, better try using a parser, like [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/).
Will the first source in PYTHONPATH always be searched first? Question: Will the sources in PYTHONPATH always be searched in the very same order as they are listed? Or may the order of them change somewhere? The specific case I'm wondering about is the view of PYTHONPATH before Python is started and if that differs to how Python actually uses it. Answer: It's actually moderately complicated. The story starts in the C code, which is what looks at `$PYTHONPATH` initially, but continues from there. In all cases, but especially if Python is being invoked as an embedded interpreter (including "framework" stuff on MacOS X), at least a little bit of "magic" is done to build up an internal path string. (When embedded, whatever is running the embedded Python interpreter can call `Py_SetPath`, otherwise python tries to figure out how it was invoked, then adjust and add `lib/pythonX.Y` where X and Y are the major and minor version numbers.) This internal path construction is done so that Python can find its own standard modules, things like `collections` and `os` and `sys`. `$PYTHONHOME` can also affect this process. In general, though, the environment `$PYTHONPATH` variable—unless suppressed via `-E`—winds up in front of the semi-magic default path. The whole schmear is used to set the initial value of `sys.path`. But then as soon as Python starts up, it loads [`site.py`](http://docs.python.org/2/library/site.html) (unless suppressed via `-S`). This modifies `sys.path` rather extensively—generally preserving things imported from `$PYTHONPATH`, in their original order, but shoving a lot of stuff (like system eggs) in front.1 Moreover, one of the things it does is load—if it exists—a per-user file `$HOME/.local/lib/pythonX.Y/sitepackages/usercustomize.py`, and _that_ can do anything, there are no guarantees: $ cat usercustomize.py print 'hello from usercustomize' $ python hello from usercustomize Python 2.7.5 (default, Jun 15 2013, 11:50:00) [GCC 4.2.1 20070831 patched [FreeBSD]] on freebsd9 Type "help", "copyright", "credits" or "license" for more information. >>> If I were to put: import random, sys random.shuffle(sys.path) this would scramble `sys.path`, putting `$PYTHONPATH` elements in random order. Arguably this is a case of "ok, you shot yourself in the foot, that's _your_ problem". :-) But anything I import can similarly mess with `sys.path`, so it's possible for something other than my own `usercustomize.py` to ruin the desired effect (of `$PYTHONPATH` ordering being preserved). * * * 1 Footnote (late edit): actually the eggs come from `site-packages/site.py`, which does its own `os.getenv("PYTHONPATH")`. So it's even messier, in a way. The general principle applies though: standard code _should_ preserve path order, but you can break it.
Managing a computation onlt with iterators Python Question: I'm trying to do this very simple thing in a more pythonistic way which would involve only one iterator: >>>for i in xrange(10): ... for j in xrange(i+1,10): ... print i,j 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 3 2 4 2 5 2 6 2 7 2 8 2 9 3 4 3 5 3 6 3 7 3 8 3 9 4 5 4 6 4 7 4 8 4 9 5 6 5 7 5 8 5 9 6 7 6 8 6 9 7 8 7 9 8 9 What I'd like to do is something like this, which would involve only one iterator: >>>from itertools import tee >>>iter1=iter(xrange(10)) >>>for i in iter1: ... iter2=tee(iter1,1)[0] ... for j in iter2: ... print i,j This obviously doesn't work, yielding: 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 Since when I've iterated all the way through iter2 I've also iterated all the way through iter1. Is there any way I can manage to achieve this ? I'm using Python-2.7 **EDIT** : What I'd like to do is the same thing with any iterable, not only numbers. Answer: Use [itertools.combinations](http://docs.python.org/2/library/itertools.html#itertools.combinations): import itertools for i, j in itertools.combinations(range(10), 2): print i, j **EDIT** correnspond to EDIT of the question itertools.combinations accept iterable. For example, >>> import itertools >>> >>> def gen(): ... yield 'egg' ... yield 'spam' ... yield 'ham' ... >>> for i, j in itertools.combinations(gen(), 2): ... print i, j ... egg spam egg ham spam ham
Python: How can I access CSV like a matrix? Question: I don't want to manually do the part of parsing the CSV and I will need to access the cell in this fashion: Cells (row, column) = X or X = Cells (row, column) Does anyone know how to do that ? Answer: numpy is nice but is a bit overkill for such a simple requirement. Try: import csv sheet = list(csv.reader(open(source_csv_location))) print sheet[0][0]
Save Matplotlib Animation Question: I am trying to make an Animation of a wave package and save it as a movie. Everything except the saving is working. Can you please tell me what I am doing wrong? When going into the line `ani.save('MovWave.mp4')` he tells me: writer = writers.list()[0] IndexError: list index out of range I tried googling it of course, but I don't even know what it means. **UPDATE:** I can call `ffmpeg` in console now. It says I have ffmpeg version `0.10.7-6:0.10.7-0jon1~precise` installed. I updated the code and ran the program, but now I get the following error: Traceback (most recent call last): ani.save('MovWave.mpeg', writer="ffmpeg") writer.grab_frame() dpi=self.dpi) self.canvas.print_figure(*args, **kwargs) self.figure.dpi = origDPI self.dpi_scale_trans.clear().scale(dpi, dpi) self._mtx = np.identity(3) from numpy import eye File "<frozen importlib._bootstrap>", line 1609, in _handle_fromlist UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte **Update 2:** Apparently there is a bug when using python 3.3 as doctorlove pointed out. I am now trying to use python 2.7 instead. Now it creates an mpeg-file but it cannot be played and it is only about ~150 kB big. **Update 3:** Okay, so I tried the exact same code on my Win7 machine and it also works in python 3.3. But I have the same problem, I had earlier with python 2.7. The mpeg-file created cannot be played and is only a few hundred kB. #! coding=utf-8 import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import time time.clock() def FFT(x,y): X = (x[-1]-x[0])/len(y) f = np.linspace(-2*np.pi/X/2,2*np.pi/X/2,len(y)) F = np.fft.fftshift(np.fft.fft(y))/np.sqrt(len(y)) return(f,F) def FUNCTION(k_0,dx,c,t): y = np.exp(1j*k_0*(x-c*t))*np.exp(-((x-c*t)/(2*dx))**2 )*(2/np.pi/dx**2)**(1/4) k,F = FFT((x-c*t),y) return(x,y,k,F) #Parameter N = 1000 x = np.linspace(0,30,N) k_0 = 5 dx = 1 c = 1 l = [k_0,c,dx] fig = plt.figure("Moving Wavepackage and it's FFT") sub1 = plt.subplot(211) sub2 = plt.subplot(212) sub2.set_xlim([-10,10]) sub1.set_title("Moving Wavepackage and it's FFT") sub1.set_ylabel("$Re[\psi(x,t)]$") sub1.set_xlabel("$t$") sub2.set_ylabel("$Re[\psi(k_x,t)]$") sub2.set_xlabel("$k_x$") n = 50 t = np.linspace(0,30,n) img = [] for i in range(n): x,y,k,F = FUNCTION(k_0,dx,c,t[i]) img.append(plt.plot(x,np.real(y),color="red", axes=plt.subplot(211))) img.append(plt.plot(k,np.real(F),color="red", axes=plt.subplot(212))) ani = animation.ArtistAnimation(fig, img, interval=20, blit=True, repeat_delay=0) ani.save('MovWave.mpeg', writer="ffmpeg") print(time.clock()) plt.show() Answer: Do you have `ffmpeg` or `mencoder` installed? Look at [this answer](http://stackoverflow.com/questions/13316397/matplotlib-animation-no- moviewriters-available/14574894#14574894) for help on installing ffmpeg.
Is there any way to make this function look nicer? Question: I need a logic that will extract a url from Apache log file: right now I did this: apache_log = {'@source': 'file://xxxxxxxxxxxxxxx//var/log/apache2/access.log', '@source_host': 'xxxxxxxxxxxxxxxxxxx', '@message': 'xxxxxxxxxxxxxxx xxxxxxxxxx - - [02/Aug/2013:12:38:37 +0000] "POST /user/12345/product/2 HTTP/1.1" 404 513 "-" "PycURL/7.26.0"', '@tags': [], '@fields': {}, '@timestamp': '2013-08-02T12:38:38.181000Z', '@source_path': '//var/log/apache2/access.log', '@type': 'Apache-access'} data = apache_log['@message'].split() if data.index('"POST') and data[data.index('"POST')+2].startswith('HTTP'): print data[data.index('"POST')+1] It returns me: /user/12345/product/2 Basically the result is correct, but the way I did it I don't really like. Can someone suggest better (more Pythonic) way of extracting this path from apache log file. Answer: A regular expression would work better: import re post_path = re.compile(r'"POST (/\S+) HTTP') match = post_path.search(apache_log['@message']) if match: print match.group(1) Demo: >>> import re >>> apache_log = {'@source': 'file://xxxxxxxxxxxxxxx//var/log/apache2/access.log', '@source_host': 'xxxxxxxxxxxxxxxxxxx', '@message': 'xxxxxxxxxxxxxxx xxxxxxxxxx - - [02/Aug/2013:12:38:37 +0000] "POST /user/12345/product/2 HTTP/1.1" 404 513 "-" "PycURL/7.26.0"', '@tags': [], '@fields': {}, '@timestamp': '2013-08-02T12:38:38.181000Z', '@source_path': '//var/log/apache2/access.log', '@type': 'Apache-access'} >>> post_path = re.compile(r'"POST (/\S+) HTTP') >>> match = post_path.search(apache_log['@message']) >>> if match: ... print match.group(1) ... /user/12345/product/2
Django unittest and mocking the requests module Question: I am new to Mock and am writing a unit test for this function: # utils.py import requests def some_function(user): payload = {'Email': user.email} url = 'http://api.example.com' response = requests.get(url, params=payload) if response.status_code == 200: return response.json() else: return None I am using [Michael Foord's Mock](http://www.voidspace.org.uk/python/mock/index.html) library as part of my unit test and am having difficulty mocking the `response.json()` to return a json structure. Here is my unit test: # tests.py from .utils import some_function class UtilsTestCase(unittest.TestCase): def test_some_function(self): with patch('utils.requests') as mock_requests: mock_requests.get.return_value.status_code = 200 mock_requests.get.return_value.content = '{"UserId":"123456"}' results = some_function(self.user) self.assertEqual(results['UserId'], '123456') I have tried numerous combinations of different mock settings after reading the docs with no luck. If I print the `results` in my unit test it always displays the following instead of the json data structure I want: <MagicMock name=u'requests.get().json().__getitem__().__getitem__()' id='30315152'> Thoughts on what I am doing wrong? Answer: Patch `json` method instead of `content`. (`content` is not used in `some_function`) Try following code. import unittest from mock import Mock, patch import utils class UtilsTestCase(unittest.TestCase): def test_some_function(self): user = self.user = Mock() user.email = '[email protected]' with patch('utils.requests') as mock_requests: mock_requests.get.return_value = mock_response = Mock() mock_response.status_code = 200 mock_response.json.return_value = {"UserId":"123456"} results = utils.some_function(self.user) self.assertEqual(results['UserId'], '123456')
How to specify which optional parameters to use in a method call? Question: I want to use optional parameter 4, not optional parameter 3. How do i specify that my 3rd parameter in my method call is supposed to use optional parameter 4 instead of default to 3? python code: from suds.client import Client client = Client('http://x.x.x.x/mywsdl.wsdl') client.service.getData("req_Param1", "req_Param2", "option_Param4") wsdl request xml: <reqparam1>?</reqparam1> <reqparam2>?</reqparam2> <!--Optional:--> <optionparam3>?</optionparam3> <!--Optional:--> <optionparam4>?</optionparam4> <!--Optional:--> <optionparam5>?</optionparam5> Parameter 3 needs to be unspecified but 4 does need to be specified. Thank you. Answer: Ah it was very simple. client.service.getData(reqparam1="req_Param1", reqparam2="req_Param2", optionparam4="option_Param4")
recursively build hierarchical JSON tree in python Question: I have a database of parent-child connections. The data look like the following but could be presented in whichever way you want (dictionaries, list of lists, JSON, etc). links=(("Tom","Dick"),("Dick","Harry"),("Tom","Larry"),("Bob","Leroy"),("Bob","Earl")) The output that I need is a hierarchical JSON tree, which will be rendered with d3. There are discrete sub-trees in the data, which I will attach to a root node. So I need to recursively go though the links, and build up the tree structure. The furthest I can get is to iterate through all the people and append their children, but I can't figure out to do the higher order links (e.g. how to append a person with children to the child of someone else). This is similar to another question [here](http://stackoverflow.com/questions/10737273/recursive-function-to- create-hierarchical-json-object), but I have no way to know the root nodes in advance, so I can't implement the accepted solution. I am going for the following tree structure from my example data. { "name":"Root", "children":[ { "name":"Tom", "children":[ { "name":"Dick", "children":[ {"name":"Harry"} ] }, { "name":"Larry"} ] }, { "name":"Bob", "children":[ { "name":"Leroy" }, { "name":"Earl" } ] } ] } This structure renders like this in my d3 layout. ![Rendered image](http://i.stack.imgur.com/1Acgc.png) Answer: To identify the root notes you can unzip `links` and look for parents who are not children: parents, children = zip(*links) root_nodes = {x for x in parents if x not in children} Then you can apply the recursive method: import json links = [("Tom","Dick"),("Dick","Harry"),("Tom","Larry"),("Bob","Leroy"),("Bob","Earl")] parents, children = zip(*links) root_nodes = {x for x in parents if x not in children} for node in root_nodes: links.append(('Root', node)) def get_nodes(node): d = {} d['name'] = node children = get_children(node) if children: d['children'] = [get_nodes(child) for child in children] return d def get_children(node): return [x[1] for x in links if x[0] == node] tree = get_nodes('Root') print json.dumps(tree, indent=4) I used a set to get the root nodes, but if order is important you can use a list and [remove the duplicates](http://stackoverflow.com/questions/10549345/how-to-remove- duplicate-items-from-a-list-using-list-comprehension).
multiple numpy version on Mac OS X Question: I am running Mac OS X 10.8.4. Python 2.7 is installed by installing command line tools in Xcode. Apple is managing a version of numpy (1.6.1) located at /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy I use sudo easy_install numpy to install a version (1.7.x). It is put at location /Library/Python/2.7/site-packages In python, when import numpy it actually imports the 1.6.1 one (managed by apple). Howe can I choose the 1.7.x one installed by `easy_install`? Answer: Use == to specify the version: easy_install numpy==1.6 I prefer pip: easy_install pip pip install numpy==1.6 EDIT: To make use of multiple installed versions of a package you could use [virtualenv](http://www.virtualenv.org/) assuming you don't need multiple versions of the package within the same project [source](http://shtuff.it/article/14/Python_- _install_specific_version_with_pip_or_easy_install)
In Django, is it possible to define a dynamically calculated setting based in another? Question: (Maybe this question is more about Python but Django is the context, so here it goes) Suppose you need a setting `FOO` whose value depends on the value of setting `BAR` (simplest case is make `CELERY_RESULT_BACKEND` equal to `BROKER_URL`). If you have only one settings file, that's simple to achieve: BAR = some_value FOO = some_function(BAR) However, it's quite popular to have many settings files, one for each environment (e.g. production, development, test, stage, etc), as proposed in the [project layout](https://github.com/twoscoops/django-twoscoops-project) from the book, "Two Scoops of Django: Best Practices for Django 1.5". In that case there is a `settings.base` module, which is imported with all its contents by `settings.dev`, `settings.prod`, etc, which add their own specific values or override those defined in `settings.base`. The problem happens when I want to override `BAR` in some of those modules, but I have to remember to recalculate `FOO` every time after that override. That's error prone and not DRY. A lambda function won't work because that setting would be a callable, not the resulting value. Built-in function/decorator [`property`](http://docs.python.org/2/library/functions.html#property) would be ideal but it can only be used within classes (new-style). I don't know anything else like that. Ideas? Answer: Yes, it is, the settings file is just a python script as well. Most people do it already to build the Template Path setting. [Django template Path](http://stackoverflow.com/questions/3038459/django- template-path) Now let's imagine this: ref = { 'dev': 'FOO', 'qa': 'BAR' 'prod': 'BAZ' } ENV = 'PROD' # Can also be DEV or QA DYNAMIC_SETTING = ref.get(ENV.lower(), None) # => 'BAZ'
Python setuptools: How can I list a private repository under install_requires? Question: I am creating a `setup.py` file for a project which depends on private GitHub repositories. The relevant parts of the file look like this: from setuptools import setup setup(name='my_project', ..., install_requires=[ 'public_package', 'other_public_package', 'private_repo_1', 'private_repo_2', ], dependency_links=[ 'https://github.com/my_account/private_repo_1/master/tarball/', 'https://github.com/my_account/private_repo_2/master/tarball/', ], ..., ) I am using `setuptools` instead of `distutils` because the latter does not support the `install_requires` and `dependency_links` arguments per [this](http://stackoverflow.com/questions/9810603/adding-install-requires-to- setup-py-when-making-a-python-package) answer. The above setup file fails to access the private repos with a 404 error - which is to be expected since GitHub returns a 404 to unauthorized requests for a private repository. However, I can't figure out how to make `setuptools` authenticate. Here are some things I've tried: 1. Use `git+ssh://` instead of `https://` in `dependency_links` as I would if installing the repo with `pip`. This fails because setuptools doesn't recognize this protocol ("unknown url type: git+ssh"), though the [distribute documentation](http://pythonhosted.org/distribute/setuptools.html#dependencies-that-aren-t-in-pypi) says it should. Ditto `git+https` and `git+http`. 2. `https://<username>:<password>@github.com/...` \- still get a 404. (This method doesn't work with `curl` or `wget` from the command line either - though `curl -u <username> <repo_url> -O <output_file_name>` does work.) 3. Upgrading setuptools (0.9.7) and virtualenv (1.10) to the latest versions. Also tried installing distribute though [this overview](http://stackoverflow.com/questions/6344076/differences-between-distribute-distutils-setuptools-and-distutils2) says it was merged back into setuptools. Either way, no dice. Currently I just have `setup.py` print out a warning that the private repos must be downloaded separately. This is obviously less than ideal. I feel like there's something obvious that I'm missing, but can't think what it might be. :) Duplicate-ish question with no answers [here](http://stackoverflow.com/questions/12956168/python-how-to-connect-to-a- protected-svn-repository-with-setuptools). Answer: Here's what worked for me: install_requires=[ 'private_package_name==1.1', ], dependency_links=[ 'git+ssh://[email protected]/username/private_repo.git#egg=private_package_name-1.1', ] Note that you have to have the version number in the egg name, otherwise it will say it can't find the package.
python import names file and sort alphabetically Question: I can't figure out why my simple names script will not work. It appears to bug out on the while loop. I might be calling it wrongly, but I figured I might try to get an answer here while I continue researching. #!/usr/bin/python #open the file name_file = open('names.txt', 'r') #read in lines names = name_file.readlines() #close file name_file.close() #loop to place names in array index = 0 while index < len(names): names[index] = names[index].rstrip('\n') index += 1 #sort names.sort() #print sorted names print names Answer: Maybe this works: with open ('names.txt', 'r') as f: names = sorted (name.rstrip ('\n') for name in f) print (names) The `with` takes care of closing the file once you leaf the scope.
swig numpy multiple matrix and array inputs Question: I'm trying interface a small C function I made into python using SWIG and the Numpy typemaps This function is defined as follows void nw(int* D, int Dx, int Dy, int* mat, int mx, int my, char *xstr, int xL,char *ystr, int yL); And my interface file is as follows %module nw %{ #define SWIG_FILE_WITH_INIT #include "nw.h" %} %include "numpy.i" %init %{ import_array(); %} /*type maps for input arrays and strings*/ %apply (int* INPLACE_ARRAY2, int DIM1, int DIM2) {(int* D, int Dx, int Dy)} %apply (int* IN_ARRAY2, int DIM1, int DIM2) {(int* mat, int mx, int my)} %apply (char* IN_ARRAY, int DIM1){(char *xstr, int xL),(char *ystr, int yL)} %include "nw.h" To test it, I used the following input D = numpy.zeros((5,5),numpy.int) mat = numpy.array([[1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1]],numpy.int) x = numpy.array(list("ABCD")) y = numpy.array(list("ABCD")) import nw nw.nw(D,mat,x,y) But when I run it, I get the following TypeError: nw() takes exactly 6 arguments (4 given) I am really confused about how these arguments are defined. Does anyone here have an idea why there are 6 arguments and what these arguments are? Thanks! Answer: Alright, I think I have figured out the problem. As it turns out, SWIG _really_ didn't like the apply directives I made for the cstrings. I should have be should the following directive instead. %apply (char *STRING, int LENGTH) {(char *xstr, int xL),(char *ystr, int yL)} Should have been following the cookbook more carefully haha
Python Request for Post in Secure website. Question: I am still learning python and this is my first go at accessing websites and scraping certain information for myself. I am trying to get my head around the language. So any input is welcome. The data below is what I am seeing from the page source. I have to visit a certain page to enter my login info. After successful entry. I am redirected to another page for my password. I am trying to make a post via python requests. I have to go through two pages before I can scrap the third page information. However, I am only able to get past the first page of login. Here is the Header and POST info that is being called for the USERNAME. For the USERNAME PAGE: (Request-Line) POST /client/factor2UserId.recip;jsessionid=15AD9CDEB48362372EFFC268C146BBFC HTTP/1.1 Host www.card.com User-Agent Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0 Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language en-US,en;q=0.5 Accept-Encoding gzip, deflate DNT 1 Referer https://www.card.com/client/ Cookie JSESSIONID=15AD9CDEB48362372EFFC268C146BBFC Connection keep-alive Content-Type application/x-www-form-urlencoded Content-Length 13 Post Data: login, USERLOGIN Here is the Header and Post info that is being called for the password: For the PASSWORD PAGE: (Request-Line) POST /client/siteLogonClient.recip HTTP/1.1 Host www.card.com User-Agent Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0 Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language en-US,en;q=0.5 Accept-Encoding gzip, deflate DNT 1 Referer https://www.card.com/client/factor2UserId.recip;jsessionid=15AD9CDEB48362372EFFC268C146BBFC Cookie JSESSIONID=15AD9CDEB48362372EFFC268C146BBFC Connection keep-alive Content-Type application/x-www-form-urlencoded Content-Length 133 Post Data: org.apache.struts.taglib.html.TOKEN, 583ed0aefe4b04b login, USERLOGIN password, PASSWORD This is what I have come up with however, I can only access the first page. I am being redirected back to the first page once I call my function second_pass(). With my function first_pass(), I receive a response code 200. However, I receive the same code on the second_pass(), but if I print out the text of the page, its a redirect to page one. I never successfully get to page three. import requests import re response = None r = None payload = {'login' : 'USERLOGIN'} # acesses the username screen and adds username # give login name def first_pass(): global response global payload url = 'https://www.card.com/client/factor2UserId.recip' s = requests.Session() response = s.post(url, payload) return response.status_code # merges payload with x that contains user password def second_pass(): global payload global r # global response x = {'password' : 'PASSWORD'} # I add the Password in this function cause I am not sure if it will fail the first_pass() payload.update(x) url = 'https://www.card.com/client/siteLogonClient.recip' r = requests.post(url, payload) return payload return r.status_code # searches response for Token! # if token found merges key:value into payload def token_search(): global response global payload f = response.text # uses regex to find the Token from the HTML patFinder2 = re.compile(r"name=\"(org.apache.struts.taglib.html.TOKEN)\"\s+value=\"(.+)\"",re.I) findPat2 = re.search(patFinder2, f) # if the Token in found it turns it into a dictionary. and prints the dictionary # if no Token is found it prints "nothing found" if(findPat2): newdict = dict(zip(findPat2.group(1).split(), findPat2.group(2).split())) payload.update(newdict) print payload else: print "No Token Found" I call my functions right now from the shell. I call them in this order. first_pass(), token_search(), second_pass(). When I call token_search(), it updates the dictionary with unicode. I am not sure if that is what is causes my errors. Any advice on the code would be most welcome. I enjoy learning. But at this point I am beating my head against the wall. Answer: If you're getting into scraping data, then I'd recommend learning about libraries like [lxml](http://lxml.de/) or [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/bs4/doc/) to more robustly gather data from pages (vs. using regex). If the token finding code works, then my recommendation would be to re-arrange the code like this. It avoids global variables, keeping variables in the scope they belong in. login('USERLOGIN', 'PASSWORD') def login(username, password): loginPayload = {'login' : username} passPayload = {'password' : password} s = requests.Session() # POST the username url = 'https://www.card.com/client/factor2UserId.recip' postData = loginPayload.copy() response = s.post(url, postData) if response.status_code != requests.codes.ok: raise ValueError("Bad response in first pass %s" % response.status_code) postData.update(passPayload) tokenParam = token_search(response.text) if tokenParam is not None: postData.update(tokenParam) else: raise ValueError("No token value found!") # POST with password and the token url = 'https://www.card.com/client/siteLogonClient.recip' r = s.post(url, postData) return r def token_search(resp_text): # uses regex to find the Token from the HTML patFinder2 = re.compile(r"name=\"(org.apache.struts.taglib.html.TOKEN)\"\s+value=\"(.+)\"",re.I) findPat2 = re.search(patFinder2, resp_text) # if the Token in found it turns it into a dictionary. and prints the dictionary # if no Token is found it prints "nothing found" if findPat2: newdict = dict(zip(findPat2.group(1).split(), findPat2.group(2).split())) return newdict else: print "No Token Found" return None
nameerror:name 'array' is not defined Question: I copy-pasted this program in pyscripter 2.7. I downloaded numpy and scipy for python 2.7 too. import numpy as np from scipy import linalg A = np.array([[1,2],[3,4]]) array([[1, 2], [3, 4]]) linalg.inv(A) array([[-2. , 1. ], [ 1.5, -0.5]]) A.dot(linalg.inv(A)) #double check array([[ 1.00000000e+00, 0.00000000e+00], [ 4.44089210e-16, 1.00000000e+00]]) but it doesn't be run and is see this: `Name Error: name 'array' is not defined`. what should I do? Answer: You seem to have attached the output in the script you are trying to run, hence the error. Executing the following gives a similar error - >>> array([1, 2]) Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> array([1, 2]) NameError: name 'array' is not defined And this matches your script. >>> A = np.array([[1, 2], [3, 4]]) >>> A array([[1, 2], [3, 4]]) Your original script is. import numpy as np from scipy import linalg A = np.array([[1,2],[3,4]]) linalg.inv(A) A.dot(linalg.inv(A)) #double check
Trying to write a python app that reads phone numbers from a file Question: I am quite new to Python. At the moment I am trying to write a script that can read a `.txt` file that contains a bunch of data, and pull out phone numbers that are in the format of `(xxx)xxx-xxxx`. Here is my current attempt, but its not working at all and I am lost: #import argv from sys import argv script, filename = argv txt_file = open(filename) indata = txt_file.read() #confirm to the user what file is being open print "Opening %r" % filename #create a loop to read through the file for line, in line enumerate(indata): if line == "(" + \w\w\w\ + ")" + \w\w\w "-" + \w\w\w print line txt_file.close() Can anyone provide me with a suggestion on how to make this work? Answer: First of all: import sys filename = sys.argv[1] #Grabs first argument #confirm to the user what file is being open print "Opening %r" % filename with open(filename,'rb') as txt_file: #Opens the file for line in txt_file: #Reads the file line by line. if #### #checks for ... Sys.argv is a list, so the first argument passed is sys.argv[1]. You don't need script because you don't use it. Don't use read() because that stores the entire file as a list and all you need to do is check each line. Use with for good measures when you're opening/writing/closing files. with closes the file as you exit the block. I'll need to see what your text file looks like to finish.
How to get json using django and jquery ajax? got 500 Intenal server error Question: I'm trying to show dynamicly details of a certain object, getting them from a sqlite3 database. I based my code on a tutorial, everything is exactly the same, but I get a 500 Internal Server Error on my page (but the tutorial runs perfectly). I have python 3.3 and django 1.6 installed. Here's my code: url.py : url(r'^cargar-inmueble/(?P<id>\d+)$', 'inmobiliaria.views.cargar_inmueble', name='cargar_inmueble_view'), views.py : import json from django.http import HttpResponse, Http404 from inmobiliaria.models import * .... def cargar_inmueble(request, id): if request.is_ajax(): inmueble = Inmueble.objects.get(id=id) return HttpResponse( json.dumps({'nombre': inmueble.nombre, 'descripcion': inmueble.descripcion, 'foto' : inmueble.foto }), content_type='application/json; charset=utf8') else: raise Http404 hover.js (it's the main js script, have to rename it) $(document).on("ready", inicio ); function inicio() { ... $("#slider ul li.inmueble").on("click", "a", cargar_inmueble); } function cargar_inmueble(data) { var id = $(data.currentTarget).data('id'); $.get('cargar-inmueble/' + id, ver_inmueble); } Looking at the console of the chrome dev tools, everytime I click the link that calls "cargar_inmueble", I get this [error](http://i.stack.imgur.com/aZyup.png) and "ver_inmueble" is never called.. It's my first web site using python so I'm pretty lost! Answer: Check network tab of chrome dev tools then you will know the source of the problem. Another way to debug is to simplify your view: def cargar_inmueble(request, id): inmueble = Inmueble.objects.get(id=id) return HttpResponse( json.dumps({'nombre': inmueble.nombre, 'descripcion': inmueble.descripcion, 'foto' : inmueble.foto }), content_type='application/json; charset=utf8') Then go to `http://localhost:8000/cargar-inmueble/1` directly and you will see the stack trace if you leave `DEBUG=True` in `settings.py`. Most likely this line can cause the error: inmueble = Inmueble.objects.get(id=id) When `id` doesn't exist, the it will throw DoesNotExist exception, you should catch it. Also I believe returning JSON is a bit different to what you are doing: def cargar_inmueble(request, id): try: inmueble = Inmueble.objects.get(id=id) except Inmueble.DoesNotExist: # catch the exception inmueble = None if inmueble: json_resp = json.dumps({ 'nombre': inmueble.nombre, 'descripcion': inmueble.descripcion, 'foto' : inmueble.foto }) else: json_resp = 'null' return HttpResponse(json_resp, mimetype='application/json') Of course you can use [`get_object_or_404`](https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#get- object-or-404) for simpler code. I just wanna show the basic idea. Hope it helps.
Is statsmodels lagmatrix function "wrong" ? (adds zeros to lagged array) Question: **Example:** Python lagmatrix([1 2 3]) returns [0 1 2] This is obviously not correct if I want to regress Y against the lagged values of Y (i.e. an AR process). I want to run a regress of Y and the lag values of Y using statsmodel.OLS but if I put NaN in the lagged verison of Y, OLS complains and doesn't run. Is there a way to run the regression without regressing `Y[1:-1]` against `lagmatrix(Y)[1:-1]` ? If I have more lags this can get annoying. How does the AR function in statsmodels find lags? Answer: I don't know what your `lagmatrix` is. I would recommend using pandas, which has a lag method and has nan handling. statsmodels has two functions that are used internally to create the lag matrices for autoregressive and vector autoregressive models and for related hypothesis tests, which have a `trim` option to choose how to treat initial and trailing observations. >>> from statsmodels.tsa.tsatools import lagmat, lagmat2ds >>> x = np.arange(10) >>> y_lagged, y = lagmat(x, maxlag=2, trim="forward", original='sep') >>> y_lagged array([[ 0., 0.], [ 0., 0.], [ 1., 0.], [ 2., 1.], [ 3., 2.], [ 4., 3.], [ 5., 4.], [ 6., 5.], [ 7., 6.], [ 8., 7.]]) >>> y array([[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]) >>> y_lagged, y = lagmat(x, maxlag=2, trim="both", original='sep') >>> y_lagged array([[ 1., 0.], [ 2., 1.], [ 3., 2.], [ 4., 3.], [ 5., 4.], [ 6., 5.], [ 7., 6.], [ 8., 7.]]) >>> y array([[2], [3], [4], [5], [6], [7], [8], [9]])
python3.2 + virtualenv - env create failed Question: I've got a py2.7 project which I want to test under py3.2. For this purpose, I want to use virtualenv. I wanted to create an environment that would run 3.2 version internally: virtualenv 3.2 -p /usr/bin/python3.2 but it failed. My default python version is `2.7` (ubuntu default settings). Here is `virtualenv --version 1.10`. The error output is: Running virtualenv with interpreter /usr/bin/python3.2 New python executable in 3.2/bin/python3.2 Also creating executable in 3.2/bin/python Installing Setuptools...................................................................................................................................................................................................................................done. Installing Pip.............. Complete output from command /home/tomasz/Develop...on/3.2/bin/python3.2 setup.py install --single-version-externally-managed --record record: Traceback (most recent call last): File "setup.py", line 5, in <module> from setuptools import setup, find_packages File "/usr/lib/python2.7/dist-packages/setuptools/__init__.py", line 2, in <module> from setuptools.extension import Extension, Library File "/usr/lib/python2.7/dist-packages/setuptools/extension.py", line 2, in <module> from setuptools.dist import _get_unpatched File "/usr/lib/python2.7/dist-packages/setuptools/dist.py", line 103 except ValueError, e: ^ SyntaxError: invalid syntax ---------------------------------------- ...Installing Pip...done. Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 2308, in <module> main() File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 821, in main symlink=options.symlink) File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 963, in create_environment install_sdist('Pip', 'pip-*.tar.gz', py_executable, search_dirs) File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 932, in install_sdist filter_stdout=filter_install_output) File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 899, in call_subprocess % (cmd_desc, proc.returncode)) OSError: Command /home/tomasz/Develop...on/3.2/bin/python3.2 setup.py install --single-version-externally-managed --record record failed with error code 1 I don't know what the hell is this syntax error - where does it come from... I know there was a change in try...catch statement syntax between 2.x and 3.x, but should virtualenv throw syntax errors? I'd be grateful if someone pointed me out if there's something I'm doing wrong or if there is an installation problem on my machine. Answer: To create a Python 3.2 virtual environment you should use the virtualenv you installed for Python 3.2. In your case that would be: /usr/bin/virtualenv-3.2
Get a c++ pointer to a Python instance using Boost::Python Question: I am working on embedding Python inside of a C++ application. When I create a new object in Python, I want to be able to store a reference to that Object in my C++ application, so that I can later call methods on that object. What's the recommended way of doing this? For Example, I would like to be able to do something like this : **Entity.py** class Entity: def getPointer(self) return pointertoSelf; **Manager.cpp** Py_Initialize(); PyRun_SimpleString("import Entity"); PyRun_SimpleString("entity = Entity.Entity()"); pointerToPythonObj* = somehowGetPointerToObj("entity"); Answer: The recommended way is to query into the namespace in which the `entity` object was created, then store a handle to the `entity` object as a [`boost::python::object`](http://www.boost.org/doc/libs/1_59_0/libs/python/doc/v2/object.html#object- spec). When interacting with Python objects from C++, it is best to use `boost::python::object` whenever possible, as it provides a high-level notation that acts much like a Python variable. Additionally, it provides the appropriate reference counting to manage the lifetime of the Python object. For example, storing a raw pointer (i.e. `pointerToPythonObj*` ) would not extend the life of the Python object; if the Python object was garbage collected from within the interpreter, then `pointerToPythonObj` would be a dangling pointer. * * * Here is an example [demonstrating](http://coliru.stacked- crooked.com/a/47ce432dd68e28be) this: Entity.py: class Entity: def action(self): print "in Entity::action" main.cpp: #include <boost/python.hpp> int main() { namespace python = boost::python; try { Py_Initialize(); // Start interpreter. // Create the __main__ module. python::object main = python::import("__main__"); python::object main_namespace = main.attr("__dict__"); // Import Entity.py, and instantiate an Entity object in the // global namespace. PyRun_SimpleString could also be used, // as it will default to running within and creating // __main__'s namespace. exec( "import Entity\n" "entity = Entity.Entity()\n" , main_namespace ); // Obtain a handle to the entity object created from the previous // exec. python::object entity = main_namespace["entity"]; // Invoke the action method on the entity. entity.attr("action")(); } catch (const python::error_already_set&) { PyErr_Print(); } } Running the above program results in the following output: in Entity::action If `Entity.py` is failing to be imported, then it may require adding its containing directory to the [`PYTHONPATH`](http://docs.python.org/2/using/cmdline.html#envvar-PYTHONPATH) environment variable.
python merge two lists (even/odd elements) Question: Given two lists, I want to merge them so that all elements from the first list are even-indexed (preserving their order) and all elements from second list are odd-indexed (also preserving their order). Example below: x = [0,1,2] y = [3,4] result = [0,3,1,4,2] I can do it using for loop. But I guess there could be a fancy pythonic way of doing this (using a less-known function or something like that). Is there any better solution that writing a for-loop? edit: I was thinking about list comprehensions, but didn't come up with any solution so far. Answer: Here's something you can use. (Use `list(izip_longest(...))` for Py2x) >>> from itertools import chain >>> from itertools import zip_longest >>> list(filter(lambda x: x != '', chain.from_iterable(zip_longest(x, y, fillvalue = '')))) [0, 3, 1, 4, 2] This works for arbitrary length lists like follows - >>> x = [0, 1, 2, 3, 4] >>> y = [5, 6] >>> list(filter(lambda x: x != '', chain.from_iterable(zip_longest(x, y, fillvalue = '')))) [0, 5, 1, 6, 2, 3, 4] **Explanation on it's working** \- 1. `zip_longest(...)` with a fill value zips the lists and fills in the given fill value for iterables of unequal length. So, for your original example, it evaluates to something like `[(0, 3), (1, 4), (2, '')]` 2. We need to flatten the result because this method gives us a list of tuples. For that we use `chain.from_iterable(...)` giving us something like `[0, 3, 1, 4, 2, '']`. 3. We now use `filter(...)` to remove all occurences of `''` and we get the required answer.
LEN error for zipping in python Question: def shufflemode(): import random combined = zip(question, answer) random.shuffle(combined) question[:], answer[:] = zip(*combined) but then i get the error: TypeError: object of type 'zip' has no len() What do I do im so confused Answer: I wonder the same thing. According to: [randomizing two lists and maintaining order in python](http://stackoverflow.com/questions/13343347/randomizing-two- lists-and-maintaining-order-in-python) You should be able to do it like the OP tried, but i also get the same error. I think the ones from the link are using python 2 and not 3, could this be the problem?
generic spider for scrapy project Question: i am creating generic spider (scrapy spider) for multiple websites. below is my project directory structure. myproject <Directory> --- __init__.py --- common.py --- scrapy.cfg --- myproject <Directory> ---__init__.py ---items.py ---pipelines.py ---settings.py ---spiders <Directory> ---__init__.py ---spider.py (generic spider) ---stackoverflow_com.py (spider per website) ---anotherwebsite1_com.py (spider per website) ---anotherwebsite2_com.py (spider per website) common.py #!/usr/bin/env python # -*- coding: UTF-8 -*- # ''' common file ''' from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from scrapy.crawler import CrawlerProcess from scrapy.stats import stats from scrapy.http import Request from WSS.items import WssItem import MySQLdb, time import urllib2, sys #Database connection def open_database_connection(): connection = MySQLdb.connect(user=db_user, passwd=db_password, db=database, host=db_host, port=db_port, charset="utf8", use_unicode=True) cursor = connection.cursor() return connection, cursor def close_database_connection(cursor, connection): cursor.close() connection.close() return class Domain_: def __init__(self, spider_name, allowed_domains, start_urls, extract_topics_xpath, extract_viewed_xpath): self.spider_name = spider_name self.extract_topics_xpath = extract_topics_xpath self.extract_viewed_xpath = extract_viewed_xpath self.allowed_domains = allowed_domains self.start_urls = start_urls spider.py #!/usr/bin/env python # -*- coding: UTF-8 -*- # from common import * class DomainSpider(BaseSpider): name = "generic_spider" def __init__(self, current_domain): self.allowed_domains = current_domain.allowed_domains self.start_urls = current_domain.start_urls self.current_domain = current_domain def parse(self, response): hxs = HtmlXPathSelector(response) for topics in list(set(hxs.select(self.current_domain.extract_topics_xpath).extract())): yield Request(topics, dont_filter=True, callback=self.extract_all_topics_data) def extract_all_topics_data(self, response): hxs = HtmlXPathSelector(response) item = WssItem() print "Processing "+response.url connection, cursor = open_database_connection() for viewed in hxs.select(self.current_domain.extract_viewed_xpath).extract(): item['TopicURL'] = response.url item['Topic_viewed'] = viewed yield item close_database_connection(cursor, connection) return stackoverflow_com.py #!/usr/bin/env python # -*- coding: UTF-8 -*- # from common import * current_domain = Domain_( spider_name = 'stackoverflow_com', allowed_domains = ["stackoverflow.com"], start_urls = ["http://stackoverflow.com/"], extract_topics_xpath = '//div[contains(@class,\"bottomOrder\")]/a/@href', extract_viewed_xpath = '//div[contains(@class,\"views\")]/text()' ) import WSS.spiders.spider as spider StackOverflowSpider = spider.DomainSpider(current_domain) from the above scripts, i don't want to touch spider.py (assuming that all websites having same structure so i can use spider.py for all spiders) i just want to create new spiders per website same as stackoverflow_com.py and i want to call spider.py for crawling process. can you please advice me is there anything wrong on my code?. it showing below error message output1: if i run "scrapy crawl stackoverflow_com" it shows below error message C:\myproject>scrapy crawl stackoverflow_com 2013-08-05 09:41:45+0400 [scrapy] INFO: Scrapy 0.16.4 started (bot: WSS) 2013-08-05 09:41:45+0400 [scrapy] DEBUG: Enabled extensions: LogStats, TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState 2013-08-05 09:41:45+0400 [scrapy] DEBUG: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, RedirectMiddleware, CookiesMiddleware, HttpCompressionMiddleware, ChunkedTransferMiddleware, DownloaderStats 2013-08-05 09:41:45+0400 [scrapy] DEBUG: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware 2013-08-05 09:41:45+0400 [scrapy] DEBUG: Enabled item pipelines: WssPipeline Traceback (most recent call last): File "C:\Python27\lib\runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "C:\Python27\lib\runpy.py", line 72, in _run_code exec code in run_globals File "C:\Python27\lib\site-packages\scrapy-0.16.4-py2.7.egg\scrapy\cmdline.py", line 156, in <module> execute() File "C:\Python27\lib\site-packages\scrapy-0.16.4-py2.7.egg\scrapy\cmdline.py", line 131, in execute _run_print_help(parser, _run_command, cmd, args, opts) File "C:\Python27\lib\site-packages\scrapy-0.16.4-py2.7.egg\scrapy\cmdline.py", line 76, in _run_print_help func(*a, **kw) File "C:\Python27\lib\site-packages\scrapy-0.16.4-py2.7.egg\scrapy\cmdline.py", line 138, in _run_command cmd.run(args, opts) File "C:\Python27\lib\site-packages\scrapy-0.16.4-py2.7.egg\scrapy\commands\crawl.py", line 43, in run spider = self.crawler.spiders.create(spname, **opts.spargs) File "C:\Python27\lib\site-packages\scrapy-0.16.4-py2.7.egg\scrapy\spidermanager.py", line 43, in create raise KeyError("Spider not found: %s" % spider_name) KeyError: 'Spider not found: stackoverflow_com' output2: if i run "scrapy crawl generic_spider" it shows below error message C:\myproject>scrapy crawl generic_spider 2013-08-05 12:25:15+0400 [scrapy] INFO: Scrapy 0.16.4 started (bot: WSS) 2013-08-05 12:25:15+0400 [scrapy] DEBUG: Enabled extensions: LogStats, TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState 2013-08-05 12:25:16+0400 [scrapy] DEBUG: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, RedirectMiddleware, CookiesMiddleware, HttpCompressionMiddleware, ChunkedTransferMiddleware, DownloaderStats 2013-08-05 12:25:16+0400 [scrapy] DEBUG: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware 2013-08-05 12:25:16+0400 [scrapy] DEBUG: Enabled item pipelines: WssPipeline Traceback (most recent call last): File "C:\Python27\lib\runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "C:\Python27\lib\runpy.py", line 72, in _run_code exec code in run_globals File "C:\Python27\lib\site-packages\scrapy-0.16.4-py2.7.egg\scrapy\cmdline.py", line 156, in <module> execute() File "C:\Python27\lib\site-packages\scrapy-0.16.4-py2.7.egg\scrapy\cmdline.py", line 131, in execute _run_print_help(parser, _run_command, cmd, args, opts) File "C:\Python27\lib\site-packages\scrapy-0.16.4-py2.7.egg\scrapy\cmdline.py", line 76, in _run_print_help func(*a, **kw) File "C:\Python27\lib\site-packages\scrapy-0.16.4-py2.7.egg\scrapy\cmdline.py", line 138, in _run_command cmd.run(args, opts) File "C:\Python27\lib\site-packages\scrapy-0.16.4-py2.7.egg\scrapy\commands\crawl.py", line 43, in run spider = self.crawler.spiders.create(spname, **opts.spargs) File "C:\Python27\lib\site-packages\scrapy-0.16.4-py2.7.egg\scrapy\spidermanager.py", line 44, in create return spcls(**spider_kwargs) TypeError: __init__() takes exactly 2 arguments (1 given) Thanking you in advance :) Answer: Try following the template from <http://doc.scrapy.org/en/latest/topics/spiders.html#spider-arguments> class DomainSpider(BaseSpider): name = "generic_spider" def __init__(self, current_domain, *args, **kwargs): self.allowed_domains = current_domain.allowed_domains self.start_urls = current_domain.start_urls super(DomainSpider, self).__init__(*args, **kwargs) self.current_domain = current_domain ...
How to use youtube-dl from a python program Question: I would like to access the result of the shell command: youtube-dl -g "www.youtube.com..." to print its output `direct url` to file; from within a python program: import youtube-dl fromurl="www.youtube.com ...." geturl=youtube-dl.magiclyextracturlfromurl(fromurl) Is that possible ? I tried to understand the mechanism in the source but got lost : `youtube_dl/__init__.py`, `youtube_dl/youtube_DL.py`, `info_extractors` ... Answer: It's not difficult and [actually documented](https://github.com/rg3/youtube- dl/blob/master/README.md#embedding-youtube-dl): import youtube_dl ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s%(ext)s'}) with ydl: result = ydl.extract_info( 'http://www.youtube.com/watch?v=BaW_jenozKc', download=False # We just want to extract the info ) if 'entries' in result: # Can be a playlist or a list of videos video = result['entries'][0] else: # Just a video video = result print(video) video_url = video['url'] print(video_url)
Nested looping over tuple values in a dictionary with tuple keys python Question: I have a defaultdict where the key is a 4-tuple (gene_region, species, ontology, length). Looping over it is simple: for gene_region, species, ontology, length in result_dict: However, I'd like to iterate over it in a nested fashion, like this: for gene_region for species for ontology ... How do I do this? Is there no other way than collecting the values first? Or using the following dum-dum way: for gene_region, _, _, _ in result_dict: for _, species, _, _ in result_dict: ... Answer: You'd have to collect all the various key elements into lists, then loop over those (using [`itertools.product()`](http://docs.python.org/2/library/itertools.html#itertools.product), preferably). The collecting can be done with `zip()`: from itertools import product gene_regions, species_plural, ontologies, lengths = zip(*result_dict) for gene_region, species, ontology, length in product(gene_regions, species_plural, ontologies, lengths): # do something with this combo. `product()` produces the same sequence of combinations as if you had nested your loops.
Python dict addition Question: I have two dicts like this, past = { '500188': { 2: {'S': 16.97011741552128, 'C': 16.97011741552128}, 3: {'S': -41.264072314989576, 'C': 'ERROR: reported_eps value not found for the year 2012.'}, 4: {'S': -40.45410186823402, 'C': 'ERROR: reported_eps value not found for the year 2012.'} }, '524715': { 2: {'S': 46.21665549733925, 'C': 38.67504905630727}, 3: {'S': -32.729615295373385, 'C': -34.21172523465267}, 4: {'S': -22.25028773515787, 'C': -36.041635048402} }, '513683': { 2: {'S': 6.319158390481139, 'C': 6.319158390481139}, 3: {'S': 19.81072942574542, 'C': 19.81072942574542}, 4: {'S': 6.367182731764687, 'C': 'ERROR: reported_eps value not found for the year 2008.'} } } future = { '500188': { 2: {'S': 16.97011741552128, 'C': 16.97011741552128}, 3: {'S': -41.264072314989576, 'C': 'ERROR: reported_eps value not found for the year 2012.'}, 4: {'S': -40.45410186823402, 'C': 'ERROR: reported_eps value not found for the year 2012.'} }, '524715': { 2: {'S': 46.21665549733925, 'C': 38.67504905630727}, 3: {'S': -32.729615295373385, 'C': -34.21172523465267}, 4: {'S': -22.25028773515787, 'C': -36.041635048402} } } to add them I have done this, def _float(value): try: return float(value) except ValueError: return 0 print {key: { year: { _type: (_float(past.get(key, {}).get(year, {}).get(_type, 0)) + _float(future.get(key, {}).get(year, {}).get(_type, 0)))/2 for _type in ['S', 'C'] }for year in [4,3,2] #Second Loop }for key in set(past.keys()+future.keys()) #First Loop } got the desired output, { '500188': { 2: {'S': 16.97011741552128, 'C': 16.97011741552128}, 3: {'S': -41.264072314989576, 'C': 0}, 4: {'S': -40.45410186823402, 'C': 0} }, '513683': { 2: {'S': 3.1595791952405694, 'C': 3.1595791952405694}, 3: {'S': 9.90536471287271, 'C': 9.90536471287271}, 4: {'S': 3.1835913658823434, 'C': 0.0} }, '524715': { 2: {'S': 46.21665549733925, 'C': 38.67504905630727}, 3: {'S': -32.729615295373385, 'C': -34.21172523465267}, 4: {'S': -22.25028773515787, 'C': -36.041635048402} } } But, there should be some better solution than this, I googled and found this similar questions, ["Adding" Dictionaries in Python?](http://stackoverflow.com/questions/1031199/adding-dictionaries-in- python) [python dict.add_by_value(dict_2)?](http://stackoverflow.com/questions/877295/python- dict-add-by-valuedict-2/1027258#1027258) but the values are in top level, but in my case the value is not in top level and I have to do a type check and have to calculate mean. what is the best way to solve this. (Python version 2.7) Answer: Working with hierarchical data as nested dicts is always going to be painful; you're better off using a library like [Pandas](http://pandas.pydata.org/): import pandas as pd, numpy as np pp = pd.Panel(past).to_frame() pf = pd.Panel(future).to_frame() pp.replace('.', 0, regex=True) + pf.replace('.', 0, regex=True) / 2 500188 513683 524715 major minor C 2 25.455176 NaN 58.012574 3 0.000000 NaN -51.317588 4 0.000000 NaN -54.062453 S 2 25.455176 NaN 69.324983 3 -61.896108 NaN -49.094423 4 -60.681153 NaN -33.375432
Python attributeError on __del__ Question: I have a python class object and I want to assign the value of one class variable class Groupclass(Workerclass): """worker class""" count = 0 def __init__(self): """initialize time""" Groupclass.count += 1 self.membercount = 0; self.members = [] def __del__(self): """delte a worker data""" Groupclass.count -= 1 if __name__ == "__main__": group1 = Groupclass() This execution result is correct, but there's an error message that says: Exception AttributeError: "'NoneType' object has no attribute 'count'" in <bound method Groupclass.__del__ of <__main__.Groupclass instance at 0x00BA6710>> ignored Can someone tell me what me I did wrong? Answer: Your `__del__` method assumes that the class is still present by the time it is called. This assumption is incorrect. `Groupclass` has already been cleared when your Python program exits and is now set to `None`. Test if the global reference to the class still exists first: def __del__(self): if Groupclass: Groupclass.count -= 1 or use `type()` to get the local reference: def __del__(self): type(self).count -= 1 but do note that this means that the semantics for `count` change if `Groupclass` is subclassed (each subclass gets a `.count` attribute versus only `Groupclass` having a `.count` attribute). Quoting from the `__del__` hook documentation: > **Warning** : Due to the precarious circumstances under which `__del__()` > methods are invoked, exceptions that occur during their execution are > ignored, and a warning is printed to `sys.stderr` instead. Also, when > `__del__()` is invoked in response to a module being deleted (e.g., when > execution of the program is done), other globals referenced by the > `__del__()` method may already have been deleted or in the process of being > torn down (e.g. the import machinery shutting down). For this reason, > `__del__()` methods should do the absolute minimum needed to maintain > external invariants. Starting with version 1.5, Python guarantees that > globals whose name begins with a single underscore are deleted from their > module before other globals are deleted; if no other references to such > globals exist, this may help in assuring that imported modules are still > available at the time when the `__del__()` method is called. If you are using Python 3, two additional notes apply: * CPython 3.3 automatically applies a [randomized hash salt](https://docs.python.org/3/reference/datamodel.html#object.__hash__) to the `str` keys used in a `globals` dictionary; this also affects the order in which globals are cleaned up, and it _could_ be that you see the problem on only _some_ of the runs. * CPython 3.4 no longer sets globals to `None` (in most cases), as per [Safe Object Finalization](https://docs.python.org/3/whatsnew/3.4.html#whatsnew-pep-442); see [PEP 442](http://www.python.org/dev/peps/pep-0442/).