|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
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
|
||||
|
||||
|
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/. > _
|
|
#32
|
|||
|
|||
|
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:
|
|
#33
|
|||
|
|||
|
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 |
|
#34
|
|||
|
|||
|
Quote:
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. |
|
#35
|
|||
|
|||
|
Quote:
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 |
|
#36
|
||||
|
||||
|
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. |
|
#37
|
||||
|
||||
|
Quote:
Here's a code sample That walks your home directory and deletes all emacs backup files (which end in ~)
__________________
~James [Not currently seeking freelance work] Like philosophy or interested in spirituality? Philosophorum. Game Dev Experts Forums Foresight Linux - Because your desktop should be cool! Linux FAQ FedoraFAQ UbuntuGuide |
|
#38
|
|||
|
|||
|
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 |
|
#39
|
|||
|
|||
|
__________________
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." "когда рак на горе свистнет" |
|
#40
|
|||
|
|||
|
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 |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > Tips, tricks, inspiration, etc |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|