How do I repeat the last command? The usual keys: Up, Ctrl+Up, Alt-p don"t work. They produce nonsensical characters.
(ve)[[email protected] ve]$ python Python 2.6.6 (r266:84292, Nov 15 2010, 21:48:32) [GCC 4.4.4 20100630 (Red Hat 4.4.4-10)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print "hello world" hello world >>> ^[[A File "<stdin>", line 1 ^ SyntaxError: invalid syntax >>> ^[[1;5A File "<stdin>", line 1 [1;5A ^ SyntaxError: invalid syntax >>> ^[p File "<stdin>", line 1 p ^ SyntaxError: invalid syntax >>>
How to repeat last command in python interpreter shell? repeat: Questions
Create list of single item repeated N times
I want to create a series of lists, all of varying lengths. Each list will contain the same element
n times (where
n = length of the list).
How do I create the lists, without using a list comprehension
[e for number in xrange(n)] for each list?
You can also write:
[e] * n
You should note that if e is for example an empty list you get a list with n references to the same list, not n independent empty lists.
At first glance it seems that repeat is the fastest way to create a list with n identical elements:
>>> timeit.timeit("itertools.repeat(0, 10)", "import itertools", number = 1000000) 0.37095273281943264 >>> timeit.timeit(" * 10", "import itertools", number = 1000000) 0.5577236771712819
But wait - it"s not a fair test...
>>> itertools.repeat(0, 10) repeat(0, 10) # Not a list!!!
itertools.repeat doesn"t actually create the list, it just creates an object that can be used to create a list if you wish! Let"s try that again, but converting to a list:
>>> timeit.timeit("list(itertools.repeat(0, 10))", "import itertools", number = 1000000) 1.7508119747063233
So if you want a list, use
[e] * n. If you want to generate the elements lazily, use
What is the best way to repeatedly execute a function every x seconds?
I want to repeatedly execute a function in Python every 60 seconds forever (just like an NSTimer in Objective C). This code will run as a daemon and is effectively like calling the python script every minute using a cron, but without requiring that to be set up by the user.
while True: # Code executed here time.sleep(60)
Are there any foreseeable problems with this code?
If your program doesn"t have a event loop already, use the sched module, which implements a general purpose event scheduler.
import sched, time s = sched.scheduler(time.time, time.sleep) def do_something(sc): print("Doing stuff...") # do your stuff s.enter(60, 1, do_something, (sc,)) s.enter(60, 1, do_something, (s,)) s.run()
If you"re already using an event loop library like
kivy, and many others - just schedule the task using your existing event loop library"s methods, instead.
Lock your time loop to the system clock like this:
import time starttime = time.time() while True: print "tick" time.sleep(60.0 - ((time.time() - starttime) % 60.0))