#31
  1. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    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.
    programming language development: www.netytan.com Hula

  2. #32
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2004
    Location
    Toronto
    Posts
    3
    Rep 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()
    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
  4. #33
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2005
    Posts
    4
    Rep 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
  6. #34
  7. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    611
    Rep Power
    65

    Smile


    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.
  8. #35
  9. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    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
  10. #36
  11. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    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.
    programming language development: www.netytan.com Hula

  12. #37
  13. fork while true;
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    May 2005
    Location
    England, UK
    Posts
    5,538
    Rep Power
    1051
    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 ~)
    [hl=python]d = path(os.environ['HOME'])
    for f in d.walkfiles('*~'):
    f.remove()[/hl]
  14. #38
  15. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    611
    Rep Power
    65

    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 ...')
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
  16. #39
  17. Recovering Intellectual
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Jun 2006
    Location
    Orange County, CA
    Posts
    1,306
    Rep Power
    785
    Very cool .. especially this:

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


    Bugs that go away by themselves come back by themselves
    Beware - your loyalty will not be rewarded
  18. #40
  19. No Profile Picture
    Gödelian monster
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Jul 1999
    Location
    Central Florida, USA
    Posts
    2,307
    Rep Power
    62

    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
  20. #41
  21. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2008
    Posts
    1
    Rep Power
    0
    Code:
    [x for x in iterable if x]
    Remove all empty elements in an iterable.

    Code:
    def foo():
      #do stuff
    
    def foo2():
      #do stuff
    
    def foo3():
      #do stuff
    
    x = {value1 : foo,
           value2 : foo2,
           value3 : foo3,}
    
    x[some_variable]()
    Who says that python doesn't have switch statements?
  22. #42
  23. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    611
    Rep Power
    65

    Wink


    Along the same line:
    Code:
    # an improved switch/case like statement to replace
    # multiple if/elif/else statements
    
    def switch_case(case):
        return "You entered " + {
        '1' : "one",
        '2' : "two",
        '3' : "three"
        }.get(case, "a bad number")
    
    num = raw_input("Input a number between 1 and 3: ")
    print switch_case(num)
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
  24. #43
  25. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2011
    Posts
    2
    Rep Power
    0
    Just started using PyCrust, i'm very impressed so far, definatly a good enough reason to install wxPython even if you don't plan on doing any GUI development!
    Last edited by jack0; March 2nd, 2011 at 08:54 PM. Reason: Removed random keywords at end
  26. #44
  27. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2012
    Posts
    3
    Rep Power
    0
    If you're going to be building a string iteratively (in a loop, for example), then instead of using string concatenation each time, the most efficient way of doing it is actually aggregating the component strings into a list and then joining them. So, for example:
  28. #45
  29. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    6
    Rep Power
    0

    stuck in equation


    hi . . my name is usama khan
    i am the student of civil engeering and we got assignment to make a project program on flexible pavement design using python.

    i know very litle about programing. still learning from tutorials. u can call me a beginner.
    now i need to solve this equation so that i can put this in python but the formula of design is very complex

    Formula is :

    log(W18) = (Z)(S)+9.36log(SN+1) -2.0+(log(dpsi/(4.5-1.5))(/(.40+1094/(SN+1)^2.5)+2.32log(Mr)-8.07

    every thing is constant except this SN. . i want to seperate SN like SN= rest of the stuff. how can i seprate it because manualy its impossible to take SN out.

    how to seperate this. show me the way i will do it myself bro. ..i dnt know much about python except if else elif and for loops. .

    plz
    so plz help me out

IMN logo majestic logo threadwatch logo seochat tools logo