multiprocessing.Process call blocks other processes from running
I'm trying to implement a script that tracks how much space certain applications are using and send a metric to a statsd service for realtime analysis however when running this code it nots forking multiple processes its still running sequential at some point the forking was working but I can't seem to figure out where I went wrong please advise I'm just trying to keep track of the growth rate of certain dirs these dirs have hundreds of thousands of files and take sometime to run I use du as it runs much faster than os.walk() and it also returns the correct compressed size on the file system pythons getsize() does not. Thanks. from datadog import initialize from datadog import api from datadog import statsd import os import subprocess from import Process, Queue from datadog import ThreadStats import time import datetime from hashlib import md5 options = { 'api_key': 'xx', 'app_key': 'xx' } def getWhispererLogsDirSize(clientcfg, queue): clientName, logPath = clientcfg.items()[0] totalSize = 0 clientResult = {} for item in os.listdir(logPath): logDir = logPath + "/" + item try: totalSize = totalSize + int(subprocess.check_output(["du","-s",logDir]).split('\t')[0]) except subprocess.CalledProcessError: print("Error processing {0} skipping.".format(logDir)) continue clientResult[clientName] = [os.path.basename(logPath),totalSize] queue.put(clientResult) return if __name__ == '__main__': title = 'Whisperer client marketdata usage' text = 'This simple utility sends whisperer logs into datadog based on client usage on disk' tags = ['version:1'] initialize(**options) #api.Event.create(title=title, text=text, tags=tags) #stats = ThreadStats() #stats.start() queue = Queue() jobs = [] clients = [ {'xx1':'/mnt/auto/glusterfs/app/NYC01-xx-PROD-01'}, {'xx2':'/mnt/auto/glusterfs/app/NYC01-xx-PROD-01'}, {'xx3':'/mnt/auto/glusterfs/app/NYC01-xx-PROD-01'}, {'xx4':'/mnt/auto/glusterfs/app/NYC01-xx-PROD-01'} ] tags = [] while True: for client in clients: stats = ThreadStats() stats.start() p = Process(target=getWhispererLogsDirSize, args=(client,queue,)) jobs.append(p) p.start() p.join() clientinfo = queue.get() clientName = clientinfo.values()[0][0] clientPath = clientinfo.keys()[0] clientLogSize = clientinfo.values()[0][1] tags = [clientName,clientPath] aggregation_key = md5(clientName).hexdigest() print(clientName, clientPath, clientLogSize) with open('/tmp/dogstatd_out.log', 'a+') as fp: fp.write("{0} {1} {2} {3}\n".format(str(datetime.datetime.now()),clientName, clientPath, clientLogSize)) stats.gauge('whisperer.marketdata.clientlogsize',int(clientLogSize),tags=tags) -- https://mail.python.org/mailman/listinfo/python-list
Word Order Simple.
You are given nn words. Some words may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification. *Note:* Each input line ends with a *"\n"* character. *Constraints:* 1≤n≤1051≤n≤105 The sum of the lengths of all the words do not exceed 106106 All the words are composed of lowercase English letters only. *Input Format* The first line contains the integer, nn. The next nn lines each contain a word. *Output Format* Output 22 lines. On the first line, output the number of distinct words from the input. On the second line, output the number of occurrences for each distinct word according to their appearance in the input. *Sample Input* 4 bcdef abcdefg bcde bcdef *Sample Output* 3 2 1 1 *Explanation* There are 3 distinct words. Here, *"bcdef"* appears twice in the input at the first and last positions. The other words appear once each. The order of the first appearances are *"bcdef"*,*"abcdefg"* and *"bcde"* which corresponds to the output. Here is my attempt I can't seem to past all test cases and not sure why? The explanation for line how to get 1 1 seems weird maybe I'm not reading it correctly. #!/usr/bin/env python3 from collections import defaultdict from collections import Counter if __name__ == '__main__': words = defaultdict(list) for i,word in enumerate(input() for x in range(int(input(: words[word].append([i+1]) count = Counter() print(len(words.keys())) for k in words: if len(words[k]) > 1: print(len(words[k]),end=' ') else: count[k] += 1 for c in count.values(): print(c,end=' ') $ cat words.txt | ./wordcount.py 3 2 1 1 ⏎ -- https://mail.python.org/mailman/listinfo/python-list
Simple exercise
>From the following input 9 BANANA FRIES 12 POTATO CHIPS 30 APPLE JUICE 10 CANDY 5 APPLE JUICE 10 CANDY 5 CANDY 5 CANDY 5 POTATO CHIPS 30 I'm expecting the following output BANANA FRIES 12 POTATO CHIPS 60 APPLE JUICE 20 CANDY 20 However my code seems be returning incorrect value #!/usr/bin/env python3 import sys import re from collections import OrderedDict if __name__ == '__main__': od = OrderedDict() recs = int(input()) for _ in range(recs): file_input = sys.stdin.readline().strip() m = re.search(r"(\w.+)\s+(\d+)", file_input) if m: if m.group(1) not in od.keys(): od[m.group(1)] = int(m.group(2)) else: od[m.group(1)] += int(od.get(m.group(1),0)) for k,v in od.items(): print(k,v) What's really going on here? $ cat groceries.txt | ./groceries.py BANANA FRIES 12 POTATO CHIPS 60 APPLE JUICE 20 CANDY 40 -- https://mail.python.org/mailman/listinfo/python-list
convert to python code
Tried a few things but can't seem to get it right any help ? let times = (...matrices) => matrices.reduce( ([a,b,c], [d,e,f]) => [a*d + b*e, a*e + b*f, b*e + c*f] ); -- https://mail.python.org/mailman/listinfo/python-list
iterating over strings seems to be really slow?
*I'm confused why the former function runs significantly faster when wc1() builds the hash on a single pass and doesn't waste memory of returning an array of strings? * *I would think wc2() to be slower what's going on here? * #!/usr/bin/env python s = The black cat jump over the bigger black cat def wc1(): word= m={} for c in s: if c != : word += c else: if m.has_key(word): m[word] += 1 else: m[word] = 1 word= return(m) def wc2(): m={} for c in s.split(): if m.has_key(c): m[c] += 1 else: m[c] = 1 return(m) if __name__ == '__main__': import timeit print(timeit.timeit(wc1(), setup=from __main__ import wc1)) print(timeit.timeit(wc2(), setup=from __main__ import wc2)) ⮀python wordcount.py 7.39647197723 3.15220093727 -- https://mail.python.org/mailman/listinfo/python-list
GO vs Python
I spent a few weeks looking at Go and have to say you can see a lot of Python's influence in Go, however my question to this list for others who are doing real work with Go and Python have you encountered any scenarios in which Go outmatched Python in terms of elegance or performance? --RB -- https://mail.python.org/mailman/listinfo/python-list
codingbat question broken?
I'm working on the following problem set from codingbat.com http://codingbat.com/prob/p107863 Given 3 int values, a b c, return their sum. However, if one of the values is 13 then it does not count towards the sum and values to its right do not count. So for example, if b is 13, then both b and c do not count. lucky_sum(1, 2, 3) → 6 lucky_sum(1, 2, 13) → 3 lucky_sum(1, 13, 3) → 1 The solution I came up with was - def lucky_sum(a, b, c): t = 0 for ints in (a, b, c): if a == 13: t = b + c elif b == 13: t = a elif c == 13: t = a + b else: t = a + b + c return t However the following tests fail lucky_sum(13, 2, 3) → 05X lucky_sum(13, 2, 13) → 015Xlucky_sum(13, 13, 2) → 015X Can anyone show me an example where all test are success? -- https://mail.python.org/mailman/listinfo/python-list
Re: SSH/Telnet program to Router/switch
Sent from my iPhone On Feb 20, 2014, at 5:59 AM, Ferrous Cranus nikos.gr...@gmail.com wrote: Τη Τετάρτη, 19 Φεβρουαρίου 2014 10:45:53 π.μ. UTC+2, ο χρήστης Wojciech Łysiak έγραψε: On 19.02.2014 09:14, Sujith S wrote: Hi, I am new to programming and python. I am looking for a python script to do ssh/telnet to a network equipment ? I know tcl/perl does this using expect/send. Do we have expect available in python as well or need to use some other method ? Hello, If you are looking for a way to connect to your netdevices and then execute some shell commands (with output) via ssh then google for paramiko module for python. It works on windows and linux. -- BR, Wojtek Hello, What will benefit the OP to go ahead and use paramiko opposed to just use Putty or another perhaps even Chrome based ssh client? Is there an advantage to that? This is a Python mailing list so obviously the OP wants to use python to automate logging into his devices and dispatching some commands. Why else would they ask here? -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: python
L On Feb 25, 2014, at 8:27 PM, Karthik Reddy challakart...@gmail.com wrote: Thank you, but from by reaserch i got these requirements .. Python, django, Twisted, MySQL, PyQt, PySide, xPython. *Technical proficiency with Python and Django. *Technical proficiency in JavaScript. *Experience with MySQL / PgSQL. *Unix/Linux expertise. *Experience with MVC design patterns and solid algorithm skills. Core Python, DJango Framework, Web2Py, Google App engine, CherryPy ( Basic Introduction) The problem for me is whether i have to learn all these technologies to work as a python developer.. Learn core python fundamentals and idioms and everything else should come easy over time with a little experience and time. On Tuesday, February 25, 2014 12:58:15 AM UTC+5:30, CM wrote: On Monday, February 24, 2014 3:31:11 AM UTC-5, Karthik Reddy wrote: I worked as a weblogic administrator and now i am changing to development and i am very much interested in python . please suggest me what are the things i need to learn more rather than python to get an I.T job. I came to know about Django but i am in a confusion please help me . I recommend you look at job advertisements in areas you'd like to work (both areas of the world and areas within IT) and see what they seem to want. Also, consider more informative subject lines to future posts. :D -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: Telnet to remote system and format output via web page
I would use something like fabric to automatically login to hosts via ssh then parse the data myself to generate static HTML pages in a document root. Having a web app execute remote commands on a server is so wrong in many ways. Sent from my iPhone On Sep 11, 2013, at 8:56 AM, Jugurtha Hadjar jugurtha.had...@gmail.com wrote: On 09/11/2013 11:45 AM, Kenroy Bennett wrote: Hi I would like to create a web app using flask or cgi library along with telnetlib to telnet to specific servers and execute commands and retrieve the output. The output will then be formatted and outputted to a webpage . Is security an issue ? How sensitive is the information you are querying ? Must it be Telnet ? -- ~Jugurtha Hadjar, -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: web development in python without using any webframework
On Aug 3, 2013, at 12:37 AM, Alok Singh Mahor alokma...@gmail.com wrote: Hello everyone, few months back I started learning python and now I got nice familiarity. now i want to use python for creating dynamic database driven websites. and I dont want to use existing web frameworks for my work. I am learning things so I wont feel lazy to write all the code myself because I want to learn. could anyone suggest me any books/site from where I can start. I want to follow MVC architecture. so please suggest me some links/book or anything thank you in advance I believe the best way to go about this is by reading and learning from other frameworks and learning how others implement core aspects of a particular approach or routine by building dynamic web frameworks. This will not only will help you learn from a working example but you will also learn how to improve upon things and make improvements over time. I would start with a simple framework like flask. Flask is extremely simple easy to use and high extendable. If one wanted to learn about building cars they wouldn't start off with spare car-parts and a engine manual -- you would be better of taking apart an old Civic and learning about the inner workings and try putting it back together this is just my 2 cents. Sent from my iPhone -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Buying a used iPhone 5
Die On Wed, Jul 10, 2013 at 6:49 AM, oswaldclem oswaldc...@gmail.com wrote: I'm planning on buying a used ATT iPhone 5 off of craigslist, and i've been reading on how some people sell their iPhones to people and later on blacklisting it, screwing the buyer over, or how people are mistakenly buying already blacklisted iPhones. I was wondering if there's a way I can prevent this? I was thinking of meeting at an ATT store to make sure it's not blacklisted and to make sure it's not connected to any account that could black list it. Would that be a good idea? - used iphone -- View this message in context: http://python.6.x6.nabble.com/Buying-a-used-iPhone-5-tp5024345.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
datetime.strptime() not padding 0's
I thought I read some where that strptime() will pad 0's for day's for some reason this isnt working for me and I'm wondering if i'm doing something wrong. from datetime import datetime dt = datetime.strptime('Apr 9 2013', '%b %d %Y') dt.day 9 How can I get strptime to run 09? instead of 9 --RB -- http://mail.python.org/mailman/listinfo/python-list
error importing modules
I'm using the fabric api (fabfile.org) I’m executing my fab script like the following: $ fab -H server set_nic_buffers -f set_nic_buffers.py Traceback (most recent call last): File /usr/lib/python2.7/site-packages/fabric/main.py, line 739, in main *args, **kwargs File /usr/lib/python2.7/site-packages/fabric/tasks.py, line 316, in execute multiprocessing File /usr/lib/python2.7/site-packages/fabric/tasks.py, line 213, in _execute return task.run(*args, **kwargs) File /usr/lib/python2.7/site-packages/fabric/tasks.py, line 123, in run return self.wrapped(*args, **kwargs) File /home/rbrown/repos/unix-tools/tools/fabfiles/nb.py, line 5, in set_nic_buffers f_exec = modules.Fabexec('set_nic_buffers', '/var/tmp/unix-tools/tools/set_nic_buffers.sh') TypeError: 'module' object is not callable My paths all seem to be fine not sure what’s going on $ python -c 'import modules.Fabexec; print (modules.Fabexec)' module 'modules.Fabexec' from 'modules/Fabexec.pyc' Fabfiles |-- modules | |-- Fabexec.py | |-- Fabexec.pyc | |-- __init__.py | `-- __init__.pyc |-- systune.py |-- systune.pyc `-- set_nic_buffers.py --- set_nic_buffers.py --- import modules from modules import Fabexec def set_nic_buffers(): f_exec = modules.Fabexec('set_nic_buffers', '/var/tmp/unix-tools/tools/set_nic_buffers.sh') f_exec.run() --- Fabexec.py --- from fabric.api import run, cd, sudo, env from fabric.contrib import files from fabric.colors import green class Fabexec(object): repobase='/var/tmp/unix-tools' def __init__(self,script_name,install_script): self.script_name = script_name self.install_script = install_script def run(self): if files.exists(self.install_script): with cd(self.repobase): result = sudo(self.install_script + ' %s ' % env.host) if result.return_code != 0: print(red('Error occured executing %s' % self.install_script)) else: print(green('%s executed successfully')) else: print(red('Error no such dir %s try running repo deploy script to host %s' % (self.repobase, env.host))) raise SystemExit() -- http://mail.python.org/mailman/listinfo/python-list
optomizations
I would like some feedback on possible solutions to make this script run faster. The system is pegged at 100% CPU and it takes a long time to complete. #!/usr/bin/env python import gzip import re import os import sys from datetime import datetime import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-f', dest='inputfile', type=str, help='data file to parse') parser.add_argument('-o', dest='outputdir', type=str, default=os.getcwd(), help='Output directory') args = parser.parse_args() if len(sys.argv[1:]) 1: parser.print_usage() sys.exit(-1) print(args) if args.inputfile and os.path.exists(args.inputfile): try: with gzip.open(args.inputfile) as datafile: for line in datafile: line = line.replace('mediacdn.xxx.com', 'media.xxx.com') line = line.replace('staticcdn.xxx.co.uk', ' static.xxx.co.uk') line = line.replace('cdn.xxx', 'www.xxx') line = line.replace('cdn.xxx', 'www.xxx') line = line.replace('cdn.xx', 'www.xx') siteurl = line.split()[6].split('/')[2] line = re.sub(r'\bhttps?://%s\b' % siteurl, , line, 1) (day, month, year, hour, minute, second) = (line.split()[3]).replace('[','').replace(':','/').split('/') datelog = '{} {} {}'.format(month, day, year) dateobj = datetime.strptime(datelog, '%b %d %Y') outfile = '{}{}{}_combined.log'.format(dateobj.year, dateobj.month, dateobj.day) outdir = (args.outputdir + os.sep + siteurl) if not os.path.exists(outdir): os.makedirs(outdir) with open(outdir + os.sep + outfile, 'w+') as outf: outf.write(line) except IOError, err: sys.stderr.write(Error unable to read or extract inputfile: {} {}\n.format(args.inputfile, err)) sys.exit(-1) -- http://mail.python.org/mailman/listinfo/python-list
Re: optomizations
On Apr 22, 2013, at 11:18 PM, Dan Stromberg drsali...@gmail.com wrote: On Mon, Apr 22, 2013 at 6:53 PM, Roy Smith r...@panix.com wrote: So, my real advice to you is to fire up the profiler and see what it says. I agree. Fire up a line-oriented profiler and only then start trying to improve the hot spots. Got a doc or URL I have no experience working with python profilers. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
The node.js Community is Quietly Changing the Face of Open Source
I came across this article which sums up some of the issues I have with modern programming languages. I've never really looked at Javascript for anything serious or Node itself but I found this article really informational. The “Batteries included” philosophy of Python was definitely the right approach during the mid 90’s and one of the reasons that I loved Python so much; this was a time before modern package management, and before it was easy to find and install community-created libraries. Nowadays though I think it’s counter-productive. Developers in the community rarely want to bother trying to compete with the standard library, so people are less likely to try to write libraries that improve upon it. http://caines.ca/blog/programming/the-node-js-community-is-quietly-changing-the-face-of-open-source/ -- http://mail.python.org/mailman/listinfo/python-list
Re: New version
Was it so hard to state in the email subject what the new version is or describe in the body a small summary on what you've released? I swear the users on this list post the most useless emails. Sent from my iPhone On Apr 9, 2013, at 7:12 AM, Jake D jhunter.dunef...@gmail.com wrote: There's a new version of im.py out on GitHub: https://github.com/jhunter-d/im.py/blob/master/im.py -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: How to choose between ORMs?
Pick the one you learn and know. Sent from my iPhone On Apr 3, 2013, at 2:17 AM, Alec Taylor alec.tayl...@gmail.com wrote: SQLalchemy and Storm are a few of the popular ORMs out there. Personally I have been using web2py's DAL. Other than form generator availability, 'print as raw SQL', multiple primary keys, widgets*, `check` conditions and compatibility with OracleDB, Postgres, SQLite and some of the NoSQL systems; what else should I be looking for? Thanks for all suggestions, Alec Taylor *not sure if widgets should be a requirement; by widgets I mean annotation of db schema to specify which widget to use with the form generator PS: Will likely use this ORM with: Flask, Bottle or Twisted Matrix -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: How to automatically get the indent level from code?
No On Sun, Mar 17, 2013 at 12:52 AM, Peng Yu pengyu...@gmail.com wrote: Hi, I want to get the indent level within the code. For example, I want to print 1 within the while loop as the line is indented 1 level. Is it possible to get it within python? while 1: #print the level of indent, which is 1 here. -- Regards, Peng -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Transparent Proxy and Redirecting Sockets
On Thu, Feb 21, 2013 at 10:24 AM, Luca Bongiorni bongi...@gmail.com wrote: Hi all, Around I have found plenty useful sources about TCP transparent proxies. However I am still missing how to make socket redirection. What I would like to do is: host_A -- PROXY -- host_B ^ | host_C -- At the beginning the proxy is simply forwarding the data between A and B. Subsequently, when a parser catches the right pattern, the proxy quit the communication between A and B and redirect all the traffic to the host_C. I would be pleased if someone would suggest me some resources or hints. Are you looking for a Python way of doing this? I would highly recommend taking a look at ha-proxy as its very robust, simple and fast. If you're looking to implement this in Python code you may want to use a framework like Twisted - http://twistedmatrix.com/trac/wiki/TwistedProject Twisted provides many functionality that can leverage to accomplish this task. Thank you :) Cheers, Luca -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
cafebabe python macosx easter egg?
$ hexdump -n4 -C $(which python) | awk '{print $2 $3 $4 $5 }' -- http://mail.python.org/mailman/listinfo/python-list
Re: Alternatives to Splunk?
On Sat, Feb 9, 2013 at 7:27 AM, sssdevelop sssdeve...@gmail.com wrote: Are there any opensource alternatives to Splunk? Need tool to analyze the log files.. This is highly off topic, however I'm using logstash + kibana for my log analysis. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
error in except
For the life of me I cant figure out why this exception is being thrown. How could I use pdb to debug this? $ python udp_local2.py server File udp_local2.py, line 36 except: ^ SyntaxError: invalid syntax #!/usr/bin/env python import random, socket, sys s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) MAX = 65535 PORT = 1060 if 2 = len(sys.argv) = 3 and sys.argv[1] == 'server': interface = sys.argv[2] if len(sys.argv) 2 else '' s.bind((interface, PORT)) print 'Listening at', s.getsockname() while True: data, address = s.recvfrom(MAX) if random.randint(0, 1): print 'The client at', address, 'says:', repr(data) s.sendto('Your data was %d bytes' % len(data), address) else: print 'Pretending to drop packet from', address elif len(sys.argv) == 3 and sys.argv[1] == 'client': hostname = sys.argv[2] s.connect((hostname, PORT)) print 'Client socket name is', s.getsockname() delay = 0.1 while True: s.send('This is another message') print 'Waiting up to', delay, 'seconds for a reply' s.settimeout(delay) try: data = s.recv(MAX) except socket.timeout: delay *= 2 if delay 2.0: raise RuntimeError('I think the server is down') except: raise else: break print 'The server says', repr(data) else: print sys.stderr, 'usage: %d server [interfae]' % sys.argv[0] print sys.stderr, ' or: %d client host' % sys.argv[0] sys.exit(2) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Class
On Friday, February 1, 2013, Charles Hoskinson wrote: I'm developing an online course for beginning python programmers starting from basic syntax through object oriented design and GUI. I'd like to include some helpful community resources like Code Academy in the appendix and I was wondering if this community has some particular favorites they would highly recommend? Udacity.com has a nice interactive CS course taught in Python. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: pyrudp
On Jan 30, 2013, at 8:12 AM, Jorge Alberto Diaz Orozco jaoro...@estudiantes.uci.cu wrote: can someone give me a link to download pyrudp. I tried here http://code.google.com/p/pyrudp/ but didn´t worked. if someone can give me another idea it will be great to. I´m traying to make a reliable udp connection What about the native socket call to SOCK_DGRAM? Here is a simple example to read messages of a udp socket. import socket UDP_IP = 127.0.0.1 UDP_PORT = 5005 sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.bind((UDP_IP, UDP_PORT)) while True: data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes print received message:, data help will be really appreciated -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: security quirk
On Tue, Jan 29, 2013 at 11:55 PM, RichD r_delaney2...@yahoo.com wrote: I read Wall Street Journal, and occasionally check articles on their Web site. It's mostly free, with some items available to subscribers only. It seems random, which ones they block, about 20%. Anywho, sometimes I use their search utility, the usual author or title search, and it blocks, then I look it up on Google, and link from there, and it loads! ok, Web gurus, what's going on? Its Gremlins! I tell you Gremlins!!! -- Rich -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Forcing Python to detect DocumentRoot
On Friday, January 18, 2013, Ferrous Cranus wrote: Τη Πέμπτη, 17 Ιανουαρίου 2013 5:14:19 μ.μ. UTC+2, ο χρήστης Joel Goldstick έγραψε: On Thu, Jan 17, 2013 at 9:09 AM, Roy Smith r...@panix.comjavascript:; wrote: In article 339d9d6d-b000-4cf3-8534-375e0c44b...@googlegroups.comjavascript:; , Ferrous Cranus nikos...@gmail.com javascript:; wrote: When trying to open an html template within Python script i use a relative path to say go one folder back and open index.html f = open( '../' + page ) How to say the same thing in an absolute way by forcing Python to detect DocumentRoot by itself? $ export DOCUMENT_ROOT=${HOME}/public _html Then from python os.environ['DOCUMENT_ROOT'] will have the relative path. I hope this helps. Can you give us more details of what you're doing. Is there some web framework you're using? Can you post some code that's not working for you? -- http://mail.python.org/mailman/listinfo/python-list Import os Then read os.environ['HOME'] This will give you the home directory of the user. in my case: os.environ['HOME'] '/home/jcg' This is probably linux only, but that seems to be the environment you are working in . Yes my Python scripts exist in a linux web host. os.environ['HOME'] will indeed give the home directory of the user. to me /home/nikos/ but i want a variable to point to /home/nikos/public_html whice is called DocumentRoot. is there avariable for that? i can't seem to find any... -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
code explanation
Can someone explain what's going on here. def _build_magic_dispatcher(method): def inner(self, *args, **kwargs): return self.__dict__[method](*args, **kwargs) inner.__name__ = method return inner Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: code explanation
On Mon, Jan 14, 2013 at 11:38 PM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: On Mon, 14 Jan 2013 23:00:16 -0500, Rodrick Brown wrote: Can someone explain what's going on here. def _build_magic_dispatcher(method): def inner(self, *args, **kwargs): return self.__dict__[method](*args, **kwargs) inner.__name__ = method return inner Thanks. This is a factory function, probably intended to be used as a decorator: class K: @_build_magic_dispatcher def something(self, x, y, z): ... except that it appears to be broken. It seems to be expecting a *string*, the name of a method, despite the function parameter claiming to require a method itself. So maybe you use it like this: class K: def __init__(self): self.parrot = _build_magic_dispatcher(parrot) or something similar. Without seeing the context, it's hard for me to tell whether it works or is broken. I suspect it is broken, or useless, or both. So, this factory function seems to take the *name* of a method as argument. Then it builds an inner method, which accepts arbitrary arguments (args and kwargs), renames the inner method to the name you passed as argument, and returns it. Thanks Steven, here is the full context of the code. I'm trying to understand what exactly the author is trying to accomplish here. import sys PY3K = sys.version_info = (3,) methods = set([ __iter__, __len__, __contains__, __lt__, __le__, __eq__, __ne__, __gt__, __ge__, __add__, __and__, __divmod__, __floordiv__, __lshift__, __mod__, __mul__, __or__, __pow__, __rshift__, __sub__, __truediv__, __xor__, ]) if PY3K: methods.add(__next__) methods.add(__bool__) else: methods.add(__div__) methods.add(__nonzero__) MAGIC_METHODS = frozenset(methods) del methods def _build_magic_dispatcher(method): def inner(self, *args, **kwargs): return self.__dict__[method](*args, **kwargs) inner.__name__ = method return inner class stub(object): _classes_cache = {} def __new__(cls, **kwargs): magic_methods_present = MAGIC_METHODS.intersection(kwargs) if magic_methods_present not in cls._classes_cache: attrs = dict( (method, _build_magic_dispatcher(method)) for method in magic_methods_present ) attrs[__module__] = cls.__module__ cls._classes_cache[magic_methods_present] = type(stub, (cls,), attrs) new_cls = cls._classes_cache[magic_methods_present] return super(stub, new_cls).__new__(new_cls, **kwargs) def __init__(self, **kwargs): self.__dict__.update(kwargs) The inner method simply looks up an attribute with the same name, and calls it as a function with whatever args and kwargs it gets. Does this help? -- Steven -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Dependency management in Python?
On Fri, Jan 11, 2013 at 5:23 PM, Adelbert Chang adelbe...@gmail.com wrote: Hi all, I've been using Python for a while now but one of my concerns is if it is possible to have some sort of dependency management (not sure if right term) for Python? In the Scala language there is the Simple Build Tool that lets me specify on a project-by-project basis which libraries I want to use (provided they are in a central repository somewhere) and it will download them for me. Better yet, when a new version comes out I need only change the SBT configuration file for that project and it will download it for me. Is there something like this for Python. I am typically wary of downloading Python modules I use like NumPy, SciPy, NetworkX, etc because I want to be able to upgrade at any time and doing so seems to be a hassle - in fact, I am not entirely sure how to upgrade. Checkout PIP/setuptools and virtualenv Thank you and regards, -Adelbert -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Class confusion
How can I make a class that has methods with attributes and other functions? I see a lot of code I'm reading the documentation to Redhat's Satellite software which has a XMLRPC interface and wrote the following code to test the api. I would like to extend this code to support methods with methods? I see this done a lot in python code but I'm not sure how to accomplish something like this? i.e. sc = SatelliteConnect() sc.get_systemlist().get_systemid() ? or sc.get_systemlist().get_running_kernel() How does one chain methods and attributes like this with classes? import xmlrpclib import os import sys class SatelliteConnect(object): SATELLITE_URL = http://nebula.nydc.fxcorp.prv/rpc/api; SATELLITE_LOGIN = os.environ['USER'] SATELLITE_PASS = os.environ.get('SATELLITE_PASS',None) def __init__(self): self.client = xmlrpclib.Server(self.SATELLITE_URL, verbose=0) self._check_env('SATELLITE_PASS') self.key = self.client.auth.login(self.SATELLITE_LOGIN, self.SATELLITE_PASS) def _check_env(self, env_var): if not os.environ.get('SATELLITE_PASS'): print({} error please set environment varible {} and re-run script.format(sys.argv[0], env_var)) sys.exit(-1) def get_runningkernel(self, sysid): self.get_systemid('somehost') kernel = self.client.system.getRunningKernel(self.key, sysid) if kernel: return kernel else: return None def get_systemlist(self): systemlist = self.client.system.listSystems(self.key) return([ system.get('name') for system in systemlist ]) self.client.auth.logout(self.key) def get_systemid(self, host): systemlist = self.client.system.getId(self.key, host) for system in systemlist: return system.get('id') -- http://mail.python.org/mailman/listinfo/python-list
Re: Class confusion
On Wed, Jan 9, 2013 at 4:34 PM, Matt Jones matt.walker.jo...@gmail.comwrote: # Something like... class SystemList(object): def get_systemid(self): return System Id: bleh def get_running_kernel(self): return Kernel: bleh class SatelliteConnect(object): def get_systemlist(self): return SystemList() # Now the code you wrote would work, only return those literals thought, you'd want to do something meaningful inside of SystemList's methods. Thanks for the tip Matt, I had no idea it was so simple. :-) *Matt Jones* On Wed, Jan 9, 2013 at 3:28 PM, MRAB pyt...@mrabarnett.plus.com wrote: On 2013-01-09 20:13, Rodrick Brown wrote: How can I make a class that has methods with attributes and other functions? I see a lot of code I'm reading the documentation to Redhat's Satellite software which has a XMLRPC interface and wrote the following code to test the api. I would like to extend this code to support methods with methods? I see this done a lot in python code but I'm not sure how to accomplish something like this? i.e. sc = SatelliteConnect() sc.get_systemlist().get_**systemid() ? or sc.get_systemlist().get_**running_kernel() How does one chain methods and attributes like this with classes? [snip] This: sc.get_systemlist().get_**systemid() simply means that the method get_systemlist returns an instance of some class (let's call it SystemList) which has a method get_systemid. -- http://mail.python.org/**mailman/listinfo/python-listhttp://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Class confusion
Can anyone care to advise on the following? Based on the responses does this look sufficient? #!/opt/local/bin/python class SystemList(object): sysmap = { '1039' : 'nebula', '1040' : 'mercury'} def __init__(self, sysid): self.sysid = sysid def get_sysname(self): return self.sysmap[self.sysid] class System(object): def __init__(self): pass def get_hostname(self,sysid): return SystemList(sysid) if __name__ == '__main__': sc = System() for sysid in ('1039','1040'): print(sc.get_hostname(sysid).get_sysname()) On Wed, Jan 9, 2013 at 5:18 PM, Rodrick Brown rodrick.br...@gmail.comwrote: On Wed, Jan 9, 2013 at 4:34 PM, Matt Jones matt.walker.jo...@gmail.comwrote: # Something like... class SystemList(object): def get_systemid(self): return System Id: bleh def get_running_kernel(self): return Kernel: bleh class SatelliteConnect(object): def get_systemlist(self): return SystemList() # Now the code you wrote would work, only return those literals thought, you'd want to do something meaningful inside of SystemList's methods. Thanks for the tip Matt, I had no idea it was so simple. :-) *Matt Jones* On Wed, Jan 9, 2013 at 3:28 PM, MRAB pyt...@mrabarnett.plus.com wrote: On 2013-01-09 20:13, Rodrick Brown wrote: How can I make a class that has methods with attributes and other functions? I see a lot of code I'm reading the documentation to Redhat's Satellite software which has a XMLRPC interface and wrote the following code to test the api. I would like to extend this code to support methods with methods? I see this done a lot in python code but I'm not sure how to accomplish something like this? i.e. sc = SatelliteConnect() sc.get_systemlist().get_**systemid() ? or sc.get_systemlist().get_**running_kernel() How does one chain methods and attributes like this with classes? [snip] This: sc.get_systemlist().get_**systemid() simply means that the method get_systemlist returns an instance of some class (let's call it SystemList) which has a method get_systemid. -- http://mail.python.org/**mailman/listinfo/python-listhttp://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
When is overriding __getattr__ is useful?
Can someone provide an example why one would want to override __getattr__ and __getattribute__ in a class? -- http://mail.python.org/mailman/listinfo/python-list
Re: how to download internet files by python ?
On Mon, Jan 7, 2013 at 11:19 PM, iMath redstone-c...@163.com wrote: for example ,if I want to download this file ,how to implement the download functionality by python ? http://down.51voa.com/201208/se-ed-foreign-students-friends-16aug12.mp3 as for download speed ,of course ,the fast ,the better ,so how to implement it ? It would be better to show me an example :) thanks !!! -- http://mail.python.org/mailman/listinfo/python-list #!/usr/bin/python import urllib2 if __name__ == '__main__': fileurl=' http://down.51voa.com/201208/se-ed-foreign-students-friends-16aug12.mp3' mp3file = urllib2.urlopen(fileurl) with open('outfile.mp3','wb') as output: output.write(mp3file.read()) -- http://mail.python.org/mailman/listinfo/python-list
Dropbox Hires Away Google’s Guido Van Rossum
http://techcrunch.com/2012/12/07/dropbox-guido-van-rossum-python/ -- http://mail.python.org/mailman/listinfo/python-list
Re: stackoverflow quote on Python
I believe this statement is correct given key differences do exist in underlying implementations even though such differences may be highly transparent to end users (developers). On Mon, Nov 12, 2012 at 10:08 PM, Mark Lawrence breamore...@yahoo.co.ukwrote: http://stackoverflow.com/**questions/tagged/pythonhttp://stackoverflow.com/questions/tagged/python Python has two major versions (2 and 3) in use which have significant differences. I believe that this is incorrect. The warts have been removed, but significant differences, not in my book. If there is agreement about there not being significant differences, should stackoverflow be asked to change their wording? -- Cheers. Mark Lawrence. -- http://mail.python.org/**mailman/listinfo/python-listhttp://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: [newbie] problem with module PyVisa
It seems pretty obvious from the error. Try installing the missing lib packages. OSError: /usr/local/vxipnp/linux/bin/libvisa.so.7: cannot open shared object file: No such file or directory Sent from my iPhone On Nov 9, 2012, at 11:22 AM, Jean Dubois jeandubois...@gmail.com wrote: OSError: /usr/local/vxipnp/linux/bin/libvisa.so.7: cannot open shared object file: No such file or directory -- http://mail.python.org/mailman/listinfo/python-list
Re: SSH Connection with Python
On Oct 25, 2012, at 6:34 AM, Schneider j...@globe.de wrote: Hi Folkz, how can i create a SSH-Connection with python? I have to send some commands to the remote host and parse their answers. greatz Johannes Fabric is the way to go! -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: system tray or notification area in python
On Oct 16, 2012, at 4:14 PM, Daniel Fetchinson fetchin...@googlemail.com wrote: Hi folks, I'm using a stand alone window manager without gnome or kde or any other de. But I still would like to have a system tray or notification area and so far used stalonetray for this. Stalonetray is written in C and is a GTK application, works all right but sometimes it doesn't. For instance if it is killed and restarted icons don't come back, etc, etc, there are some quirks. So I thought I would write a brand new stand alone system tray or notification area in python. I guess I need to use gtk bindings or some such but don't really know what my options are. Where would I start something like this? Any pointers would be greatly appreciated! Why not look at the source code of the current app your using to get an idea how that application accomplishes said task? You could always use raw X11 libs but leveraging something like Gtk or Qt/KDE would probably be much easier. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Executing untrusted scripts in a sandboxed environment
On Oct 5, 2012, at 6:32 PM, Robin Krahl m...@robin-krahl.de wrote: Hi all, I need to execute untrusted scripts in my Python application. To avoid security issues, I want to use a sandboxed environment. This means that the script authors have no access to the file system. They may only access objects, modules and classes that are flagged or approved for scripting. I read that I will not be able to do this with Python scripts. (See SandboxedPython page in the Python wiki [0] and several SE.com questions, e. g. [1].) So my question is: What is the best way to embed a script engine in a sandboxed environment that has access to the Python modules and classes that I provide? Checkout udacity.com I think there is a writeup on stackoverflow on how they accomplished their sandbox runtime env. Thanks for your help. Best regards, Robin [0] http://wiki.python.org/moin/SandboxedPython [1] http://stackoverflow.com/questions/3068139/how-can-i-sandbox-python-in-pure-python -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Can somebody give me an advice about what to learn?
On Sun, Sep 30, 2012 at 8:58 AM, tcgo tomeu...@gmail.com wrote: Hi! I'm really new to Usenet/Newsgroups, but... I'd like to learn some new programming language, because I learnt a bit of Perl though its OOP is ugly. So, after searching a bit, I found Python and Ruby, and both of they are cute. So, assuming you'll say me learn python, why should I learn it over Ruby? Thanks! Python comes stock on most Linux distro's and many RPM based distros uses Python itself as a core scripting language unlike Ruby, that's why I choose Python over Ruby 3-4 years back when I was debating which one I should learn. PS: I don't want to start a flame-war, I just want an advice if it's possible please! This is a Python mailinglist so I doubt you can ignite any flamewar's between Python vs Ruby! :) -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: For Counter Variable
On Sep 23, 2012, at 12:42 PM, jimbo1qaz jimmyli1...@gmail.com wrote: Am I missing something obvious, or do I have to manually put in a counter in the for loops? That's a very basic request, but I couldn't find anything in the documentation. for idx in list of elm: print (idx) i.e.. for idx in range(10): print(idx) -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Print Function
Go away troll! Sent from my iPhone On Sep 21, 2012, at 4:27 PM, gengyang...@gmail.com gengyang...@gmail.com wrote: Hello , I am currently using Python 3.2.3 . WHen I use the print function by typing print Game Over , it mentions SyntaxError : invalid syntax . Any ideas on what the problem is and how to resolve it ? Thanks a lot . GengYang -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: technologies synergistic with Python
On Sep 21, 2012, at 5:59 PM, Ethan Furman et...@stoneleaf.us wrote: Greetings! What is the consensus... okay, okay -- what are some wide ranging opinions on technologies that I should know if my dream job is one that consists mostly of Python, and might allow telecommuting? (Please don't say Java, please don't say Java, please don't say... ;) Django, JavaScript, HTML 5, JQuery, , SQL, Redis, Twisted ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Computing win/loss records in Python
On Aug 25, 2012, at 10:22 PM, Christopher McComas mccomas.ch...@gmail.com wrote: Greetings, I have code that I run via Django that grabs the results from various sports from formatted text files. The script iterates over every line in the formatted text files, finds the team in the Postgres database updates their w/l record depending on the outcome on that line, saves the team's row in the db, and then moves on to the next line in the file. I'm trying to get away from Django for this project, I want to run the files, get the W/L results and output a formatted text file with the teams and their W/L records. What's confusing me I guess how to store the data/results as the wins and losses tally up. We're talking hundreds of teams, thousands of games, but a quick example would be: Marshall Ohio State Kentucky Indiana Marshall,24,Ohio State,48, Kentucky,14,Indiana,10, Marshall,10,Indiana,7, Ohio State,28,Kentucky,10 That's just a quick example, I can handle seperating the data in the lines, figuring it all out, I just am unsure of how to keep a running total of a team's record. I would do for line in file: then on the first line I see that Marshall lost so they would have 1, Ohio State won so they'd have 1 win. It'd go to the next line Kentucky 1 win, Indiana 1 loss, then on the 3rd line, Marshall got a win so they'd have 1 win, but it would have to remember that loss from line 1... Does this make sense? Yes, use a RDBMS, SQLite may be the best fit for your use case its quick and has low overhead. Thanks, -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python a commercial proposition ?
Sent from my iPhone On Jul 29, 2012, at 12:07 PM, lipska the kat lip...@yahoo.co.uk wrote: Pythoners Firstly, thanks to those on the tutor list who answered my questions. I'm trying to understand where Python fits into the set of commonly available, commercially used languages of the moment. Python is a glue language much like Perl was 10 years ago. Until the GIL is fixed I doubt anyone will seriously look at Python as an option for large enterprise standalone application development. I work in financials and the majority of our apps are developed in C++ and Java yet all the tools that startup, deploy and conduct rigorous unit testing are implemented in Python or Shell scripts that wrap Python scripts. Python definitely has its place in the enterprise however not so much for serious stand alone app development. I'm starting to see Python used along side many statistical and analytical tools like R, SPlus, and Mathlab for back testing and prototype work, in a lot of cases I've seen quants and traders implement models in Python to back test and if successful converted to Java or C++. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python a commercial proposition ?
On Jul 29, 2012, at 8:54 PM, Andrew Berg bahamutzero8...@gmail.com wrote: On 7/29/2012 7:12 PM, Rodrick Brown wrote: Python is a glue language much like Perl was 10 years ago. Until the GIL is fixed I doubt anyone will seriously look at Python as an option for large enterprise standalone application development. The GIL is neither a bug to be fixed nor an inherent part of the language. It is a design choice for CPython. There are reasons the CPython devs have no intention of removing the GIL (at least in the near future). A recent outline of these reasons (written by one of the CPython devs) is here: http://python-notes.boredomandlaziness.org/en/latest/python3/questions_and_answers.html#but-but-surely-fixing-the-gil-is-more-important-than-fixing-unicode Hence the reason why no one will seriously look at Python for none glue work or simple web apps. When it comes to designing complex applications that need to exploit large multicore systems Python just isn't an option. Its still not possible to be a pure Python developer and find gainful employment today. -- CPython 3.3.0b1 | Windows NT 6.1.7601.17803 -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Keeping the Console Open with IDLE
I think you can use pythonw.exe which will read stdin and for any input before closing. (I read this a while back, ma guy here.) Sent from my iPhone On Jul 13, 2012, at 7:27 AM, summerholidaylearn...@gmail.com summerholidaylearn...@gmail.com wrote: On Friday, February 20, 2009 4:06:42 AM UTC, W. eWatson wrote: I#39;m using IDLE for editing, but execute programs directly. If there are execution or quot;compilequot; errors, the console closes before I can see what it contains. How do I prevent that? -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39° 15#39; 7quot; N, 121° 2#39; 32quot; W, 2700 feet Web Page: lt;www.speckledwithstars.net/gt; Thanks this solved my problem too(the same issue - I was also double clicking instead of right clicking - edit with IDLE - F5 to run) -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: PollyReports 1.5 -- Band-oriented PDF Report Generator
On Jul 11, 2012, at 8:44 PM, Simon Cropper simoncrop...@fossworkflowguides.com wrote: On 12/07/12 00:06, Chris Gonnerman wrote: I've held off announcing this until I was sure it was really stable; it's been 19 days since I made the last change to it, so here goes. PollyReports is my Python module for report generation. It is designed to be, quite literally, the simplest thing that can possibly work in the field of PDF generation from a database record set. There is a somewhat vague resemblance to GeraldoReports; I had problems with Geraldo's pagination which led me to develop PollyReports in a brief flurry of intense activity. It's on PyPI: http://pypi.python.org/pypi/PollyReports and on Github: https://github.com/Solomoriah/PollyReports and I have a blog where I talk about it (like anyone cares): http://opensource.gonnerman.org/?cat=4 I've noticed that acceptance of a new software module or package for developers in the Open Source/Free Software world is greatly affected by the availability of a good tutorial. I mean, it seems obvious, doesn't it? But I've also noticed that the original author of a project rarely writes a good tutorial. http://packages.python.org/PollyReports/tutorial.html The author has made the code available on Git Hub so you can easily contribute. Simple python classes and modules tend to be light on providing examples or tutorials when the docstrings may be sufficient for most. Well I thought it was a good tutorial. It certainly empowers me with enough confidence to give it a try. That said... with more than a passing interest in software and content licensing I looked at how the work was licensed. A none-standard license like this makes most people stop and think will this be a problem if I use this in my work? How compatible is your license with the main software licenses currently available? The BSD license has been around for many years even before GPL and it's quite popular amongst the anti GNU crowd. I'm not sure what you mean by non standard license? Is because it's none GPL? The BSD license is actually the most liberal open source license format available when looking to integrate open source applications into commercials ones. You're free to do as you will without tainting your software or providing your modifications you've made. -- Cheers Simon Simon Cropper - Open Content Creator Free and Open Source Software Workflow Guides Introduction http://www.fossworkflowguides.com GIS Packages http://www.fossworkflowguides.com/gis bash / Pythonhttp://www.fossworkflowguides.com/scripting -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Communication between C++ server and Python app
What interfaces are available on the server process? Sent from my iPad On Apr 28, 2012, at 8:45 PM, kenk marcin.maksym...@googlemail.com wrote: Hi, I've got a server process written in C++ running on Unix machine. On the same box I'd like to run multiple Python scripts that will communicate with this server. Can you please suggest what would be best was to achieve this ? Kind regards and thanks in advance! M. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 274
This proposal was suggested in 2001 and is only now being implemented. Why the extended delay? Sent from my iPhone On Apr 7, 2012, at 3:32 AM, Alec Taylor alec.tayl...@gmail.com wrote: Has been withdrawn... and implemented http://www.python.org/dev/peps/pep-0274/ -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Number of languages known [was Re: Python is readable] - somewhat OT
At my current firm we hire people who are efficient in one of the following and familiar with any another C#, Java, C++, Perl, Python or Ruby. We then expect developers to quickly pick up any of the following languages we use in house which is very broad. In our source repository not including the languages I've already stated above I've seen Fortran, Erlang, Groovy, HTML, CSS, JavaScript, Mathlab, C, K, R, S, Q, Excel, PHP, Bash, Ksh, PowerShell, Ruby, and Cuda. We do heavy computational and statistical analysis type work so developers need to be able to use a vast army of programming tools to tackle the various work loads were faced with on a daily basis. The best skill any developer can have is the ability to pickup languages very quickly and know what tools work well for which task. On Mar 22, 2012, at 3:14 PM, Chris Angelico ros...@gmail.com wrote: On Fri, Mar 23, 2012 at 4:44 AM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: The typical developer knows three, maybe four languages moderately well, if you include SQL and regexes as languages, and might have a nodding acquaintance with one or two more. I'm not entirely sure what you mean by moderately well, nor languages, but I'm of the opinion that a good developer should be able to learn a new language very efficiently. Do you count Python 2 and 3 as the same language? What about all the versions of the C standard? In any case, though, I agree that there's a lot of people professionally writing code who would know about the 3-4 that you say. I'm just not sure that they're any good at coding, even in those few languages. All the best people I've ever known have had experience with quite a lot of languages. ChrisA -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Odd strip behavior
#!/usr/bin/python def main(): str1='this is a test' str2='t' print .join([ c for c in str1 if c not in str2 ]) print(str1.strip(str2)) if __name__ == '__main__': main() ./remove_str.py his is a es his is a tes Why wasnt the t removed ? Sent from my iPhone -- http://mail.python.org/mailman/listinfo/python-list
Re: Odd strip behavior
On Mar 22, 2012, at 3:53 PM, Arnaud Delobelle arno...@gmail.com wrote: On Mar 22, 2012 7:49 PM, Rodrick Brown rodrick.br...@gmail.com wrote: #!/usr/bin/python def main(): str1='this is a test' str2='t' print .join([ c for c in str1 if c not in str2 ]) print(str1.strip(str2)) if __name__ == '__main__': main() ./remove_str.py his is a es his is a tes Why wasnt the t removed ? Try help(ste.strip) It clearly states if chars is given and not None, remove characters in chars instead. Does it mean remove only the first occurrence of char? That's the behavior I'm seeing. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Project
Pay a smart developer! Sent from my iPhone On Mar 7, 2012, at 4:46 AM, Dev Dixit devdixit1...@gmail.com wrote: Please, tell me how to develop project on how people intract with social networing sites. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Any Advice Would Be Greatly Appreciated
LinkedIn is an excellent resource for finding great candidates, However your problem might be because your searching for Python Developers why not hire great programmers and have them learn Python? Sent from my iPhone On Feb 29, 2012, at 6:08 PM, Greg Harezlak g...@tinyco.com wrote: Hello Python Community, I work for a mobile gaming startup in San Francisco, and we're heavily staffing around skilled Python Developers. I've already submitted a job posting to the Python.org website, but I was curious if anyone else had some suggestions on where I could go to find some really awesome people. Thanks in advance for your help. -- Greg Harezlak 1 Bush Street, 7th Floor San Francisco, CA 94104 (T): 925.683.8578 (E): g...@tinyco.com -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: python scripts solution for euler projects
On Tue, Feb 28, 2012 at 10:59 PM, scripts examples example.scri...@gmail.com wrote: Got a web site setup for solving euler problems in python, perl, ruby and javascript. Feel free to give me any feedback, thanks. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
How to handle calling functions from cli
I have a bunch of sub routines that run independently to perform various system checks on my servers. I wanted to get an opinion on the following code I have about 25 independent checks and I'm adding the ability to disable certain checks that don't apply to certain hosts. m = { 'a': 'checkDisks()', 'b': 'checkMemSize()', 'c': 'checkBondInterfaces()' } parser = argparse.ArgumentParser(description='Parse command line args.') parser.add_argument('-x', action=store, dest=d) r = parser.parse_args(sys.argv[1:]) runlist = [ c for c in m.keys() if c not in r.d ] for runable in runlist: eval(m[runable]) I'm using temp variable names for now until I find an approach I like. Is this a good approach ? It doesn't look too pretty and to be honest feels awkward? Sent from my iPhone -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Sarge, a library wrapping the subprocess module, has been released.
On Fri, Feb 10, 2012 at 2:28 PM, Vinay Sajip vinay_sa...@yahoo.co.ukwrote: Sarge, a cross-platform library which wraps the subprocess module in the standard library, has been released. What does it do? Sarge tries to make interfacing with external programs from your Python applications easier than just using subprocess alone. Sarge offers the following features: * A simple way to run command lines which allows a rich subset of Bash- style shell command syntax, but parsed and run by sarge so that you can run on Windows without cygwin (subject to having those commands available): from sarge import capture_stdout p = capture_stdout('echo foo | cat; echo bar') for line in p.stdout: print(repr(line)) ... 'foo\n' 'bar\n' * The ability to format shell commands with placeholders, such that variables are quoted to prevent shell injection attacks. * The ability to capture output streams without requiring you to program your own threads. You just use a Capture object and then you can read from it as and when you want. Advantages over subprocess --- Sarge offers the following benefits compared to using subprocess: * The API is very simple. * It's easier to use command pipelines - using subprocess out of the box often leads to deadlocks because pipe buffers get filled up. * It would be nice to use Bash-style pipe syntax on Windows, but Windows shells don't support some of the syntax which is useful, like , ||, | and so on. Sarge gives you that functionality on Windows, without cygwin. * Sometimes, subprocess.Popen.communicate() is not flexible enough for one's needs - for example, when one needs to process output a line at a time without buffering the entire output in memory. * It's desirable to avoid shell injection problems by having the ability to quote command arguments safely. * subprocess allows you to let stderr be the same as stdout, but not the other way around - and sometimes, you need to do that. Python version and platform compatibility - Sarge is intended to be used on any Python version = 2.6 and is tested on Python versions 2.6, 2.7, 3.1, 3.2 and 3.3 on Linux, Windows, and Mac OS X (not all versions are tested on all platforms, but sarge is expected to work correctly on all these versions on all these platforms). Finding out more You can read the documentation at http://sarge.readthedocs.org/ There's a lot more information, with examples, than I can put into this post. You can install Sarge using pip install sarge to try it out. The project is hosted on BitBucket at https://bitbucket.org/vinay.sajip/sarge/ And you can leave feedback on the issue tracker there. I hope you find Sarge useful! Regards, This is pretty cool I think ill check it out! I really hate working with subprocess it just seems a bit too low level for my taste. Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: standalone python web server
On Feb 8, 2012, at 11:01 PM, Rita rmorgan...@gmail.com wrote: I am building a small intranet website and I would like to use Python. I was wondering if there was a easy and medium performance python based web server available. I would like to run it on port :8080 since I wont have root access also I prefer something easy to deploy meaning I would like to move the server from one physical host to another without too much fuss. Currently, I am using flask (development server) and everything is ok but the performance is really bad. Checkout TwistedWeb it's an HTTP server that can be used as a library or standalone server. $ twistd web --path . --port 8080 -- --- Get your facts first, then you can distort them as you please.-- -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: The devolution of English language and slothful c.l.p behaviors exposed!
On Tue, Jan 24, 2012 at 1:06 AM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: On Mon, 23 Jan 2012 21:57:16 -0800, Rick Johnson wrote: Here is a grep from the month of September 2011 showing the rampantly egregious misuse of the following words and phrases: * pretty * hard * right * used to * supposed to I'm pretty sure that this news group is supposed to be for discussing the Python programming language. At least it used to be about Python. It is hard to understand why you think discussing English idioms is the right thing to do here. Especially when most programmers these wasn't taught English as their native language. -- Steven -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: unzip function?
On Wed, Jan 18, 2012 at 10:27 AM, Alec Taylor alec.tayl...@gmail.comwrote: http://docs.python.org/library/functions.html x = [1, 2, 3] y = [4, 5, 6] zipped = zip(x, y) zipped [(1, 4), (2, 5), (3, 6)] x2, y2 = zip(*zipped) x == list(x2) and y == list(y2) True Alec can you explain this behavior zip(*zipped)? -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: First python project : Tuner
You would get more responses if you used one of those sites that displayed the code right in the browser. On Tue, Jan 17, 2012 at 12:26 PM, Jérôme jer...@jolimont.fr wrote: Tue, 17 Jan 2012 08:48:13 -0800 (PST) Rick Johnson a écrit: On Jan 17, 8:16 am, Jérôme jer...@jolimont.fr wrote: Any comment is welcome, be it about code optimization, coding style, pythonification, good practices, or simply program features and usability. Step one would be to show a screen shot in both English AND French language. The screenshot was a dissatisfying mix of english and french because until I18n is done (next in TODO list) all the strings are in english, but the stock buttons are localized as my system is in french. Yet the inconsistency. I didn't know it was as easy as LANGUAGE=EN ./tuner_v2_0.py to re-localize a program. Now the screenshot is english only. Anyway, I was trying to bring people's attention to the python program itself : http://devs.jolimont.fr/tuner/downloads/tuner_v2_0.py Besides, not everyone in this community is a card carrying pacifist. ? -- Jérôme -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
thread example question
Can any idea help me figure out why the following output is sequential? I'm running this example on a 4 core system. I would expect the output to look random. import _thread as thread import time class thread_counter(object): def __init__(self, thr_cnt, sleep_int): self.thr_cnt = thr_cnt self.sleep_int = sleep_int def counter(myId, count): for i in range(count): time.sleep(1) print('[{}] = {}'.format(myId, i)) def main(): for i in range(5): thread.start_new_thread(counter, (i, 5)) time.sleep(6) print('Main thread exiting..') if __name__ == '__main__': main() [0] = 0 [0] = 1 [0] = 2 [0] = 3 [0] = 4 Main thread exiting.. [1] = 0 [1] = 1 [1] = 2 [1] = 3 [1] = 4 Main thread exiting.. [2] = 0 [2] = 1 [2] = 2 [2] = 3 [2] = 4 Main thread exiting.. [3] = 0 [3] = 1 [3] = 2 [3] = 3 [3] = 4 Main thread exiting.. [4] = 0 [4] = 1 [4] = 2 [4] = 3 [4] = 4 Main thread exiting.. -- http://mail.python.org/mailman/listinfo/python-list
import issue with classes
I have a class FooB that derives from FooA i.e. class FooB(FooA): FooA.__init__(self,...) Can someone explain why Import FooA doesn't work and I need to use from FooA import FooA instead? This puzzles me. Thanks. -- [ Rodrick R. Brown ] http://www.linkedin.com/in/rodrickbrown -- http://mail.python.org/mailman/listinfo/python-list
Re: Execute a command on remote machine in python
You could easily script this with popen calling secure shell to execute a command and capture the output. Sent from my iPhone On Nov 15, 2011, at 7:04 AM, Roark suha...@gmail.com wrote: Hi, I am first time trying my hands on python scripting and would need some guidance from the experts on my problem. I want to execute a windows command within python script from a client machine on a remote target server, and would want the output of the command written in a file on client machine. What is the way it could be achieved. Thanks in advance, Roark. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: PC locks up with list operations
$ man limits.conf Sent from my iPhone On Aug 31, 2011, at 8:33 AM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: Twice in a couple of weeks, I have locked up my PC by running a Python 2.5 script that tries to create a list that is insanely too big. In the first case, I (stupidly) did something like: mylist = [0]*12345678901234 After leaving the machine for THREE DAYS (!!!) I eventually was able to get to a console and kill the Python process. Amazingly, it never raised MemoryError in that time. The second time was a little less stupid, but not much: mylist = [] for x in itertools.combinations_with_replacement(some_big_list, 20): mylist.append(func(x)) After three hours, the desktop is still locked up. I'm waiting to see what happens in the morning before rebooting. Apart from Then don't do that!, is there anything I can do to prevent this sort of thing in the future? Like instruct Python not to request more memory than my PC has? I am using Linux desktops; both incidents were with Python 2.5. Do newer versions of Python respond to this sort of situation more gracefully? -- Steven -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Stop quoting spam [was Re: Hot Girls ...]
It's not the end of the world calm down I thought it was quite funny for a friday joke! Sent from my iPhone On Aug 19, 2011, at 4:43 PM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: Matty Sarro wrote: That's great - but do they program in python? Thanks for that, I didn't see the spam the first time, but thanks to your joke I saw it now! I really appreciate that, because I LOVE to have spam sent to me, including all the URLs. An extra bonus is that when the posting is archived on a couple of dozen websites, this will boost the spammer's Google rankings. Thanks heaps! Your joke was so worth it. Not. [spam deleted] -- Steven -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
How to deal with optional argument evaluation
I'm having a hard time dealing with the following scenario My class takes a hash like the following: rdargs = {'env:'prod','feed':'opra','hostname':'host13dkp1','process':'delta','side':'a','zone','ny'} All the keys in this hash can be optional. I'm having a hard time dealing with all 36 possible combinations and I dont want to use a monstorous if not and else or etc... to evaluate all possible combinations before I call my search routine. How do others deal with situations like this? And have it look readable? if someone supplies just a host and side my search can return 400 responses, if they supply all 6 elements it can return just 1-5 matches. class RD(object): def __init__(self,**kwargs): self.value = 0 #for field in ('env', 'side', 'zone', 'feed', 'hostname', 'process', 'status'): #val = kwargs[field] if kwargs.has_key(field) else False #setattr(self, field, val) self.env = kwargs.get('env',False) self.side = kwargs.get('side',False) self.zone = kwargs.get('zone',False) self.feed = kwargs.get('feed',False) self.hostname = kwargs.get('hostname',False) self.process = kwargs.get('process',False) self.status = kwargs.get('status',False) -- [ Rodrick R. Brown ] http://www.rodrickbrown.com http://www.linkedin.com/in/rodrickbrown -- http://mail.python.org/mailman/listinfo/python-list
Re: ENVIRONMENT Variable expansion in ConfigParser
How about doing something like host.name=%HOSTNAME% Then when you parse in the value %HOSTNAME% from your configParser module you do a pattern substitution of %HOSTNAME% with os.environ['HOSTNAME']. Sent from my iPhone 4. On Oct 14, 2010, at 7:57 PM, pikespeak krishnan.snowboar...@gmail.com wrote: Hi, I am using ConfigParser module and would like to know if it has the feature to autoexpand environment variables. For example currently, I have the below section in config where hostname is hardcoded. I would like it to be replaced with the values from the env variable os.envion['HOSTNAME'] so that I can remove hardcoding and my config will be host independent. [section] host.name=devserver1.company.com to be replaced with something like this [section] host.name=os.environ['HOSTNAME'] I know of the interpolation feature of Config Parser %{foo}s where value of foo will be expanded..but not sure if this can be tweeked to my needs. Any ideas please. srini -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
sending commands to the unix shell
Trying to do something very trivial why is it failing I've tried three approaches 1. os.system(/bin/cat %s | /bin/mail -s \'connection error\' %s % (logFile,notifyList)) 2. os.system(/bin/mail -s \'connection error\' %s %s % (notifyList,logFile)) 3. p1 = sp.Popen([/bin/cat, logFile], stdout=sp.PIPE) p2 = sp.Popen([/bin/mail, -s, error, notifyList], stdin=p1.stdout, stdout=sp.PIPE) Please help and explain why all 3 methods fail. -- [ Rodrick R. Brown ] http://www.rodrickbrown.com http://www.linkedin.com/in/rodrickbrown -- http://mail.python.org/mailman/listinfo/python-list
How do you preserve time values with date.datefromtimestamp()
I'm doing something like today = datetime.date.fromtimestamp(1284584357.241863) today.ctime() 'Wed Sep 15 00:00:00 2010' Why isn't the time field being populated what I expect is to see something like Wed Sep 15 2010 16:59:17:241863 -- [ Rodrick R. Brown ] http://www.rodrickbrown.com http://www.linkedin.com/in/rodrickbrown -- http://mail.python.org/mailman/listinfo/python-list
Re: WMI in Python
The easiest way to do this is to use the native OS tools readily available to do the collection and log to a central location or if possible shared location accessible by all systems, once you have all the data you want to feed into your RDBMS you could easily parse these logs using python and the native db access module. I hope this give you a pointer. Sent from my iPhone 4. On Sep 13, 2010, at 8:45 AM, KING LABS kinglabs...@gmail.com wrote: Hi All, I am new to programming and python, Being a system administrator I have chose Inventory (Software Hardware ) as my first project. I would like to know experts advice on the best way to build the same using python. I would like to this tool to evolve into full fledge application. I would like to collect the complete information of system hardware and also software installed from registry and add/remove program and feed this data into database. Regards, KINGLABS -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Open a command pipe for reading
I have a fairly large file 1-2GB in size that I need to process line by line but I first need to convert the file to text using a 3rd party tool that prints the records also line by line. I've tried using Popen to do this with no luck. I'm trying to simulate /bin/foo myfile.dat And as the records are being printed do some calculations. pipe = Popen(exttool,shell=True,stdout=PIPE).stdout for data in pipe.readlines(): print data, This operation blocks forever I'm guessing it's trying to process the entire file at once. Sent from my iPhone 4. -- http://mail.python.org/mailman/listinfo/python-list
0 length field in time string
Anyone know why I'm getting the following error when trying to parse the following string is there a better method to use? #57=2010081708240065 - sample string passed to fmt_datetime def fmt_datetime(tag57): tag57 = tag57[3:len(tag57)] year= int ( tag57[0:4] ) mon = int ( tag57[4:6] ) day = int ( tag57[6:8]) hour= int ( tag57[8:10] ) min = int ( tag57[10:12] ) sec = int ( tag57[12:14] ) msec= int ( tag57[14:16] ) dt = datetime.datetime(year,mon,day,hour,min,sec) return '{:%Y-%m-%d %H:%M:%S}'.format(dt) File ./delta_delay.py, line 27, in fmt_datetime return '{:%Y-%m-%d %H:%M:%S}'.format(dt) ValueError: zero length field name in format -- http://mail.python.org/mailman/listinfo/python-list
Re: measuring a function time
Someone should port Perl's Benchmark.pm module to python that's such a useful module to measure a functions execution time and CPU usage. Sent from my iPhone 4. On Jul 29, 2010, at 3:43 PM, Benjamin J. Racine bjrac...@glosten.com wrote: I just use ipython's functions (that are themselves just calls to the time module functions) for timing my functions... Enter: %timeit? or %time At the Ipython command prompt to get started. Ben R. On Jul 29, 2010, at 7:43 AM, D'Arcy J.M. Cain wrote: On Thu, 29 Jul 2010 08:45:23 -0400 Joe Riopel goo...@gmail.com wrote: On Thu, Jul 29, 2010 at 8:34 AM, Mahmood Naderan nt_mahm...@yahoo.com wrote: the output should be 7600 (s) for example. What is the best and easiest way to do that? Take a look at time.clock() I don't know if that's what he wants. The clock() method returns processor time, not wall time. Python 2.6.5 (r265:79063, Jul 8 2010, 16:01:18) [GCC 4.1.3 20080704 prerelease (NetBSD nb2 20081120)] on netbsd5 Type help, copyright, credits or license for more information. from time import time, clock, sleep t = time() print time() - t, clock() 0.000596046447754 0.03 sleep(3) print time() - t, clock() 3.03474903107 0.03 x = open(BIGFILE).read() print time() - t, clock() 10.2008538246 1.42 -- D'Arcy J.M. Cain da...@druid.net | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiline regex
Slurp the entire file into a string and pick out the fields you need. Sent from my iPhone 4. On Jul 21, 2010, at 10:42 AM, Brandon Harris brandon.har...@reelfx.com wrote: I'm trying to read in and parse an ascii type file that contains information that can span several lines. Example: createNode animCurveTU -n test:master_globalSmooth; setAttr .tan 9; setAttr -s 4 .ktv[0:3] 101 0 163 0 169 0 201 0; setAttr -s 4 .kit[3] 10; setAttr -s 4 .kot[3] 10; createNode animCurveTU -n test:master_res; setAttr .tan 9; setAttr .ktv[0] 103 0; setAttr .kot[0] 5; createNode animCurveTU -n test:master_faceRig; setAttr .tan 9; setAttr .ktv[0] 103 0; setAttr .kot[0] 5; I'm wanting to grab the information out in chunks, so createNode animCurveTU -n test:master_faceRig; setAttr .tan 9; setAttr .ktv[0] 103 0; setAttr .kot[0] 5; would be what my regex would grab. I'm currently only able to grab out the first line and part of the second line, but no more. regex is as follows my_regexp = re.compile(createNode\ animCurve.*\n[\t*setAttr.*\n]*) I've run several variations of this, but none return me all of the expected information. Is there something special that needs to be done to have the regexp grab any number of the setAttr lines without specification? Brandon L. Harris -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with movie module
Did you try emailing the author of this application? 2010/7/6 Jose Ángel Quintanar Morales ssq...@gmail.com Hi, I'm sorry by my bad english. I have a little problem with pygame.movie module when I try work whit him show this problem [josean...@qumax reproductor]$ python packbox.py packbox.py:64: RuntimeWarning: use mixer: No module named mixer (ImportError: No module named mixer) pygame.mixer.quit() Traceback (most recent call last): File packbox.py, line 98, in module main() File packbox.py, line 95, in main publicidad_show(screen) File packbox.py, line 64, in publicidad_show pygame.mixer.quit() File /usr/lib/python2.6/site-packages/pygame/__init__.py, line 70, in __getattr__ raise NotImplementedError(MissingPygameModule) NotImplementedError: mixer module not available (ImportError: No module named mixer) anybody help me please, I'm search in the web and I found this email list. thanks José angel -- http://mail.python.org/mailman/listinfo/python-list -- [ Rodrick R. Brown ] http://www.rodrickbrown.com http://www.linkedin.com/in/rodrickbrown -- http://mail.python.org/mailman/listinfo/python-list
Re: pprint
On Wed, Jun 9, 2010 at 5:01 AM, madhuri vio madhuri@gmail.com wrote: sir what is the function of pprint??? could you please help me out with that -- madhuri :) rbr...@laptop:~$ python Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type help, copyright, credits or license for more information. import pprint print pprint.__doc__ Support to pretty-print lists, tuples, dictionaries recursively. Very simple, but useful, especially in debugging data structures. Classes --- PrettyPrinter() Handle pretty-printing operations onto a stream using a configured set of formatting parameters. Functions - pformat() Format a Python object into a pretty-printed representation. pprint() Pretty-print a Python object to a stream [default is sys.stdout]. saferepr() Generate a 'standard' repr()-like value, but protect against recursive data structures. -- http://mail.python.org/mailman/listinfo/python-list -- [ Rodrick R. Brown ] http://www.rodrickbrown.com http://www.linkedin.com/in/rodrickbrown -- http://mail.python.org/mailman/listinfo/python-list
Re: Programing family
Don't forget his little brother Go! Sent from my iPhone 3GS. On Feb 8, 2010, at 8:39 PM, AON LAZIO aonla...@gmail.com wrote: I have thought funny things If we think all languages are like a family I could draft them like this (Python base) C is Python's Mom C++ : Dad Pascal/Assembly : Grandparents C# : Uncle Java : Ant Ruby: Cousin Perl : Girlfriend What u guys think? XD -- Passion is my style -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Do I have to use threads?
On Tue, Jan 5, 2010 at 11:26 PM, aditya shukla adityashukla1...@gmail.comwrote: Hello people, I have 5 directories corresponding 5 different urls .I want to download images from those urls and place them in the respective directories.I have to extract the contents and download them simultaneously.I can extract the contents and do then one by one. My questions is for doing it simultaneously do I have to use threads? Please point me in the right direction. Threads in python are very easy to work with but not very efficient and for most cases slower than running multiple processes. Look at using multiple processes instead of going with threads performance will be much better. Thanks Aditya -- http://mail.python.org/mailman/listinfo/python-list -- [ Rodrick R. Brown ] http://www.rodrickbrown.com http://www.linkedin.com/in/rodrickbrown -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about an application
Take a look at ssh Sent from my iPhone 3GS. On Jan 4, 2010, at 12:50 AM, rieh25 robertoedw...@gmail.com wrote: I am thinking of installing a python webserver I coded in every computer at my work. This would allow me to run specific tasks in them, like creating backups, installing things, etc. Is there another way to run programs in remote computers? Thanks for your opinions. -- View this message in context: http://old.nabble.com/Question-about-an-application-tp27009118p27009118.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Thread performance on Python 2.6
I started dabbling with threads in python and for some odd reason the performance seems extremely poor on my 2 core system. It this a simplified version spawn 2 threads write some data to a file and time the results vs doing the same sequentially. Why is the performance so much slower with the threaded version? #!/usr/bin/python import time from threading import Thread from tempfile import NamedTemporaryFile BYTES=1000 class FileWriterThread(Thread): def __init__(self,filenam): Thread.__init__(self) self.filenam = filenam def run(self): self.filename = NamedTemporaryFile(delete=False) start = time.time() for count in xrange(1,BYTES): self.filename.write(str(count)) self.filename.write(\n) end = time.time() return (end - start) def fileWriter(bytesToWrite): f = NamedTemporaryFile(delete=False) start = time.time() for n in xrange(1,bytesToWrite): f.write(str(n)) f.write(\n) end = time.time() return (end - start) if __name__ == __main__: #tmpfile = NamedTemporaryFile(delete=False) total = 0.0 start = time.time() for x in xrange(2): c = FileWriterThread(BYTES) c.start() c.join() end = time.time() print Runtime (thread based): %f % (end - start) for x in xrange(2): c = fileWriter(BYTES) print Runtime (None thread based): %f % c total += c print Total Runtime (None thread based): %f % total rbr...@laptop:~/code/python$ python filewriter_thr.py Runtime (thread based): 66.721260 Runtime (None thread based): 16.52 Runtime (None thread based): 16.078885 Total Runtime (None thread based): 32.078937 rbr...@laptop:~/code/python$ grep ^cpu.*cores /proc/cpuinfo cpu cores : 2 cpu cores : 2 -- [ Rodrick R. Brown ] http://www.rodrickbrown.com http://www.linkedin.com/in/rodrickbrown -- http://mail.python.org/mailman/listinfo/python-list
Re: Author of a Python Success Story Needs a Job!
Move to NYC, Chicago, or Boston and try to land a job working in the financial industry they're always hiring and Python is getting very popular amongst the quantitative and computation finance sectors. You may need to use head hunters two I recommended are Connections NY, Open Systems, and Tek Systems. I wish you the best its difficult everywhere. On Mon, Dec 28, 2009 at 2:32 AM, Andrew Jonathan Fine eternalsqu...@hotmail.com wrote: To whom it may concern, I am the author of Honeywell Avoids Documentation Costs with Python and other Open Standards! I was laid off by Honeywell several months after I had made my presentation in the 2005 Python Conference. Since then I have been unable to find work either as a software engineer or in any other capacity, even at service jobs. I've sent resumes and have been consistently ignored. What I have been doing in the meantime is to be a full time homemaker and parent. As a hobby to keep me sane, I am attempting to retrain part time at home as a jeweler and silversmith, and I sometimes used Python for generating and manipulating code for CNC machines. For my own peace of mind, however, I very much want to be doing software work again because I feel so greatly ashamed to have dedicated my life to learning and working in the field only to now find myself on the scrap heap. I find it highly ironic that my solution is still being advertised on the Python web site but that I, the author of that solution, am now a long term unemployment statistic. Please, if there is anyone out there who needs a highly creative and highly skilled software designer for new and completely original work, then for the love of God I implore you to contact me. A mind is a terrible thing to waste. Sincerely, Andrew Jonathan Fine BEE, MSCS, 15 years experience, 5 in Python, the rest in C/C++, about 1/3 embedded design and device drivers, and 2/3 in applications. -- http://mail.python.org/mailman/listinfo/python-list -- [ Rodrick R. Brown ] http://www.rodrickbrown.com http://www.linkedin.com/in/rodrickbrown -- http://mail.python.org/mailman/listinfo/python-list
Queues vs List
Was reading the official python document and I noticed they mentioned queues being more efficient for adding/removing elements vs list so I wrote a quick test the validate this claim and I wasn't very impressed by the results it seems queues are just slightly faster so my question to the list, is deque used much in python over general lists? 1 #!/usr/bin/python 2 3 import time 4 from collections import deque 5 6 nameList = [Eric,John,Michael] 7 #queue = deque([Eric,John,Michael]) 8 queue = deque(nameList) 9 10 def buildItems_q(q,n,mode): 11 start = 0 12 end = 0 13 14 if mode == 'q': 15 start = time.time() 16 for r in xrange(n): 17 queue.append(Terry_%s % r) 18 end = time.time() 19 20 while q.pop() is not None: 21 try: 22 q.pop() 23 except IndexError: 24 pass 25 break 26 else: 27 start = time.time() 28 for r in xrange(n): 29 q.append(Terry_%s % r) 30 end = time.time() 31 32 while q.pop() is not None: 33 try: 34 q.pop() 35 except IndexError: 36 pass 37 break 38 39 return (end - start) 40 41 if __name__ == __main__: 42 size = 1000 43 mode = 'list' 44 runtime = buildItems_q(queue,size,mode) 45 print Total run time: %f (%s) % (runtime,mode) 46 47 mode = 'Queue' 48 runtime = buildItems_q(queue,size,mode) 49 print Total run time: %f (%s) % (runtime,mode) rbr...@laptop:~/code/python$ python queue.py Total run time: 5.169290 (list) Total run time: 5.112517 (Queue) -- [ Rodrick R. Brown ] http://www.rodrickbrown.com http://www.linkedin.com/in/rodrickbrown -- http://mail.python.org/mailman/listinfo/python-list
Testing for empty list
p=[] if p is None: ... print 'yes' ... This doesn't work as expected. -- [ Rodrick R. Brown ] http://www.rodrickbrown.com http://www.linkedin.com/in/rodrickbrown -- http://mail.python.org/mailman/listinfo/python-list