Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me
Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
Stop making mediocre tutorials.The best tutorials are video! Camtasia Studio makes it easy to create engaging, buzz-building screen videos at any size, in any popular format. Download the free trial!
  #31  
Old February 24th, 2005, 04:39 PM
netytan's Avatar
netytan netytan is offline
Hello World :)
Dev Shed Regular (2000 - 2499 posts)
 
Join Date: Mar 2003
Location: Hull, UK
Posts: 2,479 netytan User rank is Sergeant Major (2000 - 5000 Reputation Level)netytan User rank is Sergeant Major (2000 - 5000 Reputation Level)netytan User rank is Sergeant Major (2000 - 5000 Reputation Level)netytan User rank is Sergeant Major (2000 - 5000 Reputation Level)netytan User rank is Sergeant Major (2000 - 5000 Reputation Level)netytan User rank is Sergeant Major (2000 - 5000 Reputation Level) 
Time spent in forums: 1 Week 2 Days 7 h 39 m 48 sec
Reputation Power: 46
Send a message via ICQ to netytan Send a message via AIM to netytan Send a message via MSN to netytan Send a message via Yahoo to netytan
This is a follow up to my last post about Mac OS X clickable Python programs. As I mentioned there seemed to be a problem running Python programs from the Script Menu, I've since figured out that the script is run however it is run in the background and not in the Terminal like you would expect .

It is possible to wrap the Python program in a simple Applescript to force the script to open it in Terminal

Note: This can even be done from the command line using one of the osa* commands.

This is probably overkill unless you need to interact with the program – supply input – in which case I would suggest that you just do some typing and run it from the command line .

It is also handy to redirect stdout to a specified file so that you can read any results from there. This can be done something like this:

Code:
#!/usr/bin/env python

import sys

sys.stdout = file('/Users/User/Documents/example.txt', 'w')

...


This can be done with any of the standard file handles but I'n the case of stderr I suggest that you get the program working before adding it to the Script Menu since the lack of Terminal Window makes spotting errors troublesome at best.

Have fun all,

Mark.
__________________
...
> (define links (list google scheme ruby python others ...)) ; Read my blog at http://netytan.blogspot.com/.
> _



Reply With Quote
  #32  
Old February 24th, 2005, 06:10 PM
cgreb cgreb is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2004
Location: Toronto
Posts: 3 cgreb User rank is Sergeant (500 - 2000 Reputation Level)cgreb User rank is Sergeant (500 - 2000 Reputation Level)cgreb User rank is Sergeant (500 - 2000 Reputation Level)cgreb User rank is Sergeant (500 - 2000 Reputation Level)cgreb User rank is Sergeant (500 - 2000 Reputation Level) 
Time spent in forums: 32 m 40 sec
Reputation Power: 0
Timing with decorators

I've found the new (2.4) 'decorator' feature to be quite useful for abstracting away 'aspects' as they say:
(based on an earlier post about timing)

Code:
import time

def print_timing(func):
    def wrapper(*arg):
        t1 = time.clock()
        res = func(*arg)
        t2 = time.clock()
        print '%s took %sms.' % (func.func_name, (t2-t1)*1000.)
        return res
    return wrapper

@print_timing        
def f1():
    x=[]
    for i in xrange(1,10000):
        x.append(str(i))
    s = ''.join(x)

@print_timing
def f2():
    x=''
    for i in xrange(1, 10000):
        x += str(i)

if __name__ == '__main__':
    f1()
    f2()

Quote:
Result:
f1 took 17.1052466165ms.
f2 took 18.325234073ms.

You can see how nicely you could use this for logging, synchonization, contracts, etc..
Comments on this post
netytan agrees: A beautiful design and a great use of decorators!
LinuxPenguin agrees: That's one of the best uses i've found for decorators - great work and elegant too

Reply With Quote
  #33  
Old June 11th, 2005, 10:39 AM
kyleb kyleb is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Jun 2005
Posts: 4 kyleb User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 52 m 19 sec
Reputation Power: 0
Operator overloading

Python supports operator overloading, and does so with methods of a class.

For example, you can add 2 objects together with __add__. But, you SHOULD create a new object of the class BEFORE adding........__iadd__ excludes that suggestion.

Code:
class Foo:
  def __init__(self, integer=0):
    if not isinstance(integer, int):
      try:
        integer = int(integer)
      except: raise
    self.i = integer
  def __add__(self, other): # new = self + other
    new = self.__class__() # 1. Create
    if isinstance(other, self.__class__): # 2. Check
      new.i = other.i
    else: raise ValueError("foo+other: Incompatible type addition (got %s, expected %s)" % (other, self.__class__.__name__))
    return new # 3. Return
  def __iadd__(self, other): self += other
    if  isinstance(other, self.__class__):
      self.i = other.i
      return self
    else:
      raise ValueError("foo+=other: Incompatible type addition (got %s, expected %s)" % (other, self.__class__.__name__))


As you can see, there is a constitent way to object addition, subtraction, etc. See http://www.python.org/doc/2.1.3/ref/numeric-types.html

Reply With Quote
  #34  
Old July 15th, 2005, 03:37 PM
Dietrich Dietrich is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Feb 2005
Posts: 305 Dietrich User rank is Sergeant (500 - 2000 Reputation Level)Dietrich User rank is Sergeant (500 - 2000 Reputation Level)Dietrich User rank is Sergeant (500 - 2000 Reputation Level)Dietrich User rank is Sergeant (500 - 2000 Reputation Level)Dietrich User rank is Sergeant (500 - 2000 Reputation Level) 
Time spent in forums: 1 Day 23 h 5 m 27 sec
Reputation Power: 21
Smile

Quote:
Originally Posted by cgreb
I've found the new (2.4) 'decorator' feature to be quite useful for abstracting away 'aspects' as they say:
(based on an earlier post about timing)

Code:
import time

def print_timing(func):
    def wrapper(*arg):
        t1 = time.clock()
        res = func(*arg)
        t2 = time.clock()
        print '%s took %sms.' % (func.func_name, (t2-t1)*1000.)
        return res
    return wrapper

@print_timing        
def f1():
    x=[]
    for i in xrange(1,10000):
        x.append(str(i))
    s = ''.join(x)

@print_timing
def f2():
    x=''
    for i in xrange(1, 10000):
        x += str(i)

if __name__ == '__main__':
    f1()
    f2()

Shouldn't ...
Code:
print '%s took %sms.' % (func.func_name, (t2-t1)*1000.)

... be something like...
Code:
print '%s took %0.3fms.' % (func.func_name, (t2-t1)*1000.)

For some odd reason the %s works even though (t2-t1)*1000 gives a float. The wonders of Python! Maybe that is supposed to be the real trick!

By the way, if you run that code a few times the results flip all over. Sometimes f1() is faster than f2(), other times it's the reverse.

Reply With Quote
  #35  
Old July 17th, 2005, 02:12 PM
DevCoach DevCoach is offline
Contributing User
Dev Shed Beginner (1000 - 1499 posts)
 
Join Date: Feb 2004
Location: London, England
Posts: 1,174 DevCoach User rank is Captain (20000 - 30000 Reputation Level)DevCoach User rank is Captain (20000 - 30000 Reputation Level)DevCoach User rank is Captain (20000 - 30000 Reputation Level)DevCoach User rank is Captain (20000 - 30000 Reputation Level)DevCoach User rank is Captain (20000 - 30000 Reputation Level)DevCoach User rank is Captain (20000 - 30000 Reputation Level)DevCoach User rank is Captain (20000 - 30000 Reputation Level)DevCoach User rank is Captain (20000 - 30000 Reputation Level)DevCoach User rank is Captain (20000 - 30000 Reputation Level) 
Time spent in forums: 1 Week 5 Days 6 h 3 m 45 sec
Reputation Power: 207
Quote:
Originally Posted by Dietrich
For some odd reason the %s works even though (t2-t1)*1000 gives a float. The wonders of Python! Maybe that is supposed to be the real trick!


It is not some odd reason, it is by design. The %s operator will convert any operand to a string (using its __str__ method) and display the result. There is also a %r operator that converts it using repr instead.

e.g.
Code:
Python 2.4.1 (#1, May 27 2005, 18:02:40)
[GCC 3.3.3 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print '-%s-' % 123
-123-
>>> print '-%s-' % 'hello'
-hello-
>>> print '-%s-' % 123.456
-123.456-
>>> print '-%r-' % 'hello'
-'hello'-
>>> print '-%s-' % Exception
-exceptions.Exception-
>>> print '-%r-' % Exception
-<class exceptions.Exception at 0x46526c>-
>>>


Dave - The Developers' Coach

Reply With Quote
  #36  
Old July 17th, 2005, 06:42 PM
netytan's Avatar
netytan netytan is offline
Hello World :)
Dev Shed Regular (2000 - 2499 posts)
 
Join Date: Mar 2003
Location: Hull, UK
Posts: 2,479 netytan User rank is Sergeant Major (2000 - 5000 Reputation Level)netytan User rank is Sergeant Major (2000 - 5000 Reputation Level)netytan User rank is Sergeant Major (2000 - 5000 Reputation Level)netytan User rank is Sergeant Major (2000 - 5000 Reputation Level)netytan User rank is Sergeant Major (2000 - 5000 Reputation Level)netytan User rank is Sergeant Major (2000 - 5000 Reputation Level) 
Time spent in forums: 1 Week 2 Days 7 h 39 m 48 sec
Reputation Power: 46
Send a message via ICQ to netytan Send a message via AIM to netytan Send a message via MSN to netytan Send a message via Yahoo to netytan
The jumping around likely has something to do with how the time.clock() function works on different platforms; in any case using time.time() in its place with a few mod's should fix the problem .

Take care,

Mark.

Reply With Quote
  #37  
Old February 15th, 2007, 08:21 AM
LinuxPenguin's Avatar
LinuxPenguin LinuxPenguin is offline
fork while true;
Dev Shed God 1st Plane (5500 - 5999 posts)
 
Join Date: May 2005
Location: England, UK
Posts: 5,535 LinuxPenguin User rank is General (90000 - 100000 Reputation Level)LinuxPenguin User rank is General (90000 - 100000 Reputation Level)LinuxPenguin User rank is General (90000 - 100000 Reputation Level)LinuxPenguin User rank is General (90000 - 100000 Reputation Level)LinuxPenguin User rank is General (90000 - 100000 Reputation Level)LinuxPenguin User rank is General (90000 - 100000 Reputation Level)LinuxPenguin User rank is General (90000 - 100000 Reputation Level)LinuxPenguin User rank is General (90000 - 100000 Reputation Level)LinuxPenguin User rank is General (90000 - 100000 Reputation Level)LinuxPenguin User rank is General (90000 - 100000 Reputation Level)LinuxPenguin User rank is General (90000 - 100000 Reputation Level)LinuxPenguin User rank is General (90000 - 100000 Reputation Level)LinuxPenguin User rank is General (90000 - 100000 Reputation Level)LinuxPenguin User rank is General (90000 - 100000 Reputation Level)LinuxPenguin User rank is General (90000 - 100000 Reputation Level)LinuxPenguin User rank is General (90000 - 100000 Reputation Level)  Folding Points: 11590 Folding Title: Novice Folder
Time spent in forums: 1 Month 3 Weeks 1 Day 19 h 23 m 58 sec
Reputation Power: 999
Quote:
Originally Posted by sf2k
For newb's like me. Seems to me that time and time again I'm looking through the string and os modules. Get to know them. They are your friends.

If you do a lot of file processing, knowing the os module (there's a lot) makes using the filesystem a breeze. If you ever have to work with string constants, look at the string module. Odds are it's already there. (ie: string.digits, string.punctuation etc)

So for example, I was making a general utility to search all my source files for a phrase inside my code. (I forget where I put stuff right?) Checked the os module. Sure enough, I found os.walk, (os.path.walk < 2.3) which was immediately useful for my code. This is a recursive search, taking a walk down each tree branch from whatever starting point. I can't imagine how much time this has saved me. Sweet.

Cheers
sf2k
Isn't os.path.walk the single most annoying function in the world? No longer fear it, I saw this and thought of Jason Orendorff's path module

Here's a code sample That walks your home directory and deletes all emacs backup files (which end in ~)
python Code:
Original - python Code
  1. d = path(os.environ['HOME'])
  2. for f in d.walkfiles('*~'):
  3.     f.remove()

Reply With Quote
  #38  
Old August 14th, 2007, 01:33 PM
Dietrich Dietrich is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Feb 2005
Posts: 305 Dietrich User rank is Sergeant (500 - 2000 Reputation Level)Dietrich User rank is Sergeant (500 - 2000 Reputation Level)Dietrich User rank is Sergeant (500 - 2000 Reputation Level)Dietrich User rank is Sergeant (500 - 2000 Reputation Level)Dietrich User rank is Sergeant (500 - 2000 Reputation Level) 
Time spent in forums: 1 Day 23 h 5 m 27 sec
Reputation Power: 21
Talking

Just a few tricks you can play with the homely input() function:
Code:
# input() actually uses raw_input() and then tries to
# convert the input data to a number using eval()
# this leads to some unexpected results

x = 123
a = input('Enter x: ')
# if the user enters the character x instead of a value then a = 123, try it
print a

b = input('Enter 355/113.0 : ')
# eval() will give b the result of the math expression, can be useful
print b

# this would be the more dangerous side of input() and its hidden partner eval()
# eval() evaluates this statement and executes it
# and will actually create a new directory on your C drive, somewhat harmless
# but a troublemaker could enter a similar statement to wipe out files!!!!
z = input("Enter  __import__('os').mkdir('C:/Aatest')  : ")

c = input('Enter "Hello" : ')
# since "Hello" is a string it will be passed on to c (who needs raw_input()?)
print c, type(c)

d = input('Enter a list like [1,2,3] : ')
# you guessed it, d will be a list, can be useful
print d, type(d)

# this will give an error since eval() doesn't know what to do with just enter
z = input('Press Enter ...')
__________________
small mind, large car

Reply With Quote
  #39  
Old August 14th, 2007, 02:55 PM
Matt1776 Matt1776 is offline
Recovering Intellectual
Dev Shed Novice (500 - 999 posts)
 
Join Date: Jun 2006
Location: Orange County, CA
Posts: 789 Matt1776 User rank is Major (30000 - 40000 Reputation Level)Matt1776 User rank is Major (30000 - 40000 Reputation Level)Matt1776 User rank is Major (30000 - 40000 Reputation Level)Matt1776 User rank is Major (30000 - 40000 Reputation Level)Matt1776 User rank is Major (30000 - 40000 Reputation Level)Matt1776 User rank is Major (30000 - 40000 Reputation Level)Matt1776 User rank is Major (30000 - 40000 Reputation Level)Matt1776 User rank is Major (30000 - 40000 Reputation Level)Matt1776 User rank is Major (30000 - 40000 Reputation Level)Matt1776 User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 3 Weeks 1 Day 3 m 49 sec
Reputation Power: 309
Very cool .. especially this:

python Code:
Original - python Code
  1. z = input("Enter  __import__('os').mkdir('C:/Aatest')  : ")


__________________
Bugs that go away by themselves come back by themselves
"Its called the American dream, cause you have to be asleep to believe it ...." --George Carlin
"Yeah, well, sometimes nothin' can be a real cool hand."
"когда рак на горе свистнет"

Reply With Quote
  #40  
Old September 13th, 2007, 02:52 PM
rycamor rycamor is offline
Gödelian monster
Dev Shed Regular (2000 - 2499 posts)
 
Join Date: Jul 1999
Location: Pembroke Pines, Florida, USA
Posts: 2,298 rycamor User rank is Sergeant Major (2000 - 5000 Reputation Level)rycamor User rank is Sergeant Major (2000 - 5000 Reputation Level)rycamor User rank is Sergeant Major (2000 - 5000 Reputation Level)rycamor User rank is Sergeant Major (2000 - 5000 Reputation Level)rycamor User rank is Sergeant Major (2000 - 5000 Reputation Level)rycamor User rank is Sergeant Major (2000 - 5000 Reputation Level) 
Time spent in forums: 3 Days 1 h 54 m 21 sec
Reputation Power: 41
iPython -- nice shell

I know it's been mentioned a few times in this forum, but it should be stuck here: use ipython for an interactive shell rather than 'python'.

Do this especially if you envy the Ruby shell (irb), with it's introspection and helpful shortcuts. Python's default shell is nowhere near this helpful, but iPython has most of the advantages of irb and a few extras.

- tab-completion for classes, objects, and methods, as well as local filesystem searching
- "help [function]" brings up a nice help menu
- "? [classname]" brings up a quick class description with docstring
- nicely colorized/formatted output

This is just the beginning. Take a look at the full list of features.
__________________
The real n-tier system:

FreeBSD -> PostgreSQL -> [any_language] -> Apache -> Mozilla/XUL

Amazon wishlist -- rycamor (at) gmail.com

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPython Programming > Tips, tricks, inspiration, etc


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump