Re: How can I make a program automatically run once per day?
On Jul 14, 7:00 pm, monkeys paw wrote: > On 7/9/2011 10:01 PM, John Salerno wrote: > > > Thanks everyone! I probably should have said something like "Python, > > if possible and efficient, otherwise any other method" ! :) > > > I'll look into the Task Scheduler. Thanks again! > > You could use the below code. time.sleep(# seconds in a day) > where i == 30 would run once a day for a month > > import time > i=0 > while (1): > print 'hello' > time.sleep(2) # Change this to number of seconds in a day > if (i == 3): # make this 30 for a month > break > i = i + 1 This looks like a bad idea to me: to make it work throughout the year you need to adjust for daylight savings start and end; this is where a day does not have 24 hours - and, of course, daylight savings depends on country settings of your host system... Andreas bal...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Threading with Socket Server
If you don't mind to use the coroutine library eventlet you can implement a single threaded solution. See example below. For your use case you need to change controller to load the shelve every eventlet.sleep(n) seconds. Regards, Andreas # eventlet single thread demo """ prc_publish.eventlet Price Publisher """ # imports from argparse import ArgumentParser import eventlet import logging import os import random import sys import cPickle as pickle LOG = logging.getLogger() # definitions def main(argv=None): if argv is None: argv = sys.argv LOG.info("starting '%s %s'", os.path.basename(argv[0]), " ".join(argv[1:])) # parse options and arguments parser = ArgumentParser(description="Price Publisher") parser.add_argument("-f", "--file", dest="filename", help="read configuration from %(dest)s") parser.add_argument("-p", "--port", default=8001, type=int, help="server port [default: %(default)s") args = parser.parse_args() print args # create product dict prds = { } pubqs = [] for n in range(10): key = "AB" + "{:04}".format(n) prds["AB" + key] = Pricer(key) # start one thread for price changes eventlet.spawn(controller, prds, pubqs) address = ('localhost', 8010) eventlet.spawn(listener, address, pubqs) # main thread runs eventlet loop while True: eventlet.sleep(10) def listener(address, pubqs): sock = eventlet.listen(address) while True: LOG.info('waiting for connection on %s', address) cx, remote = sock.accept() LOG.info("accepting connection from %s", remote) inq = eventlet.queue.Queue() pubqs.append(inq) eventlet.spawn(receiver, cx) eventlet.spawn(publisher, pubqs, inq, cx) def publisher(pubqs, inq, cx): LOG.info("Publisher running") try: while True: # what happens if client does not pick up # what happens if client dies during queue wait try: with eventlet.Timeout(1): item = inq.get() s = pickle.dumps(item, pickle.HIGHEST_PROTOCOL) # s = "{0[0]} {0[1]}\n\r".format(item) cx.send(s) except eventlet.Timeout: # raises IOError if connection lost cx.fileno() # if connection closes except IOError, e: LOG.info(e) # make sure to close the socket finally: cx.close() pubqs.remove(inq) LOG.info("Publisher terminated") def receiver(cx): LOG.info("Receiver running") try: while True: # what happens if client does not pick up s = cx.recv(4096) if not s: break LOG.info(s) # if connection closes except IOError, e: LOG.info(e) # make sure to close the socket finally: cx.close() LOG.info("Receiver terminated") def controller(prds, pubqs): while True: LOG.info("controller: price update cycle, %i pubqs", len(pubqs)) Pricer.VOLA = update_vola(Pricer.VOLA) for prd in prds.values(): prd.run() for pubq in pubqs: pubq.put((prd.name, prd.prc)) eventlet.sleep(5) def update_vola(old_vola): new_vola = max(old_vola + random.choice((-1, +1)) * 0.01, 0.01) return new_vola class Pricer(object): VOLA = 0.01 def __init__(self, name): self.name = name self.prc = random.random() * 100.0 def run(self): self.prc += random.choice((-1, +1)) * self.prc * self.VOLA if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)03i %(levelname). 4s %(funcName)10s: %(message)s', datefmt='%H:%M:%S') main() -- http://mail.python.org/mailman/listinfo/python-list
Re: which "dictionary with attribute-style access"?
On Oct 22, 6:34 am, "Gabriel Genellina" wrote: > > class AttrDict(dict): > > """A dict whose items can also be accessed as member variables.""" > > def __init__(self, *args, **kwargs): > > dict.__init__(self, *args, **kwargs) > > self.__dict__ = self > > > def copy(self): > > return AttrDict(self) > > > def __repr__(self): > > return 'AttrDict(' + dict.__repr__(self) + ')' > > > �...@classmethod > > def fromkeys(self, seq, value = None): > > return AttrDict(dict.fromkeys(seq, value)) > > Looks fine as long as nobody uses an existing method name as adictionary > key: > > py> d = AttrDict({'name':'value'}) > py> d.items() > [('name', 'value')] > py> d = AttrDict({'items': [1,2,3]}) > py> d.items() > Traceback (most recent call last): > File "", line 1, in > TypeError: 'list' object is not callable > > (I should have included a test case for this issue too). > Of course, if this doesn't matter in your application, go ahead and use > it. Just be aware of the problem. > > -- > Gabriel Genellina I see two ways to avoid collisions with existing method names: 1. (easy, reduced functionality) override __setattr__ and __init__, test for keys matching existing method names, throw an exception if exists (KeyError). 2. (complex, emulates dict) override __setattr__ and __init__, test for keys matching existing method names, and store those keys in a shadow dict. More problems arise when thinking about how to choose access between dict method names and item keys. -- Andreas Balogh baloand at gmail dot com -- http://mail.python.org/mailman/listinfo/python-list
Re: remote control firefox with python
On Nov 28, 4:22 pm, News123 wrote: > Hi, > > I wondered whether there is a simpe way to > 'remote' control fire fox with python. > > With remote controlling I mean: > - enter a url in the title bar and click on it > - create a new tab > - enter another url click on it > - save the html document of this page > - Probably the most difficult one: emulate a click or 'right click' on a > certain button or link of the current page. > - other interesting things would be to be able to enter the master > password from a script > - to enable disable proxy settings while running. > > The reason why I want to stay within Firefox and not use any other > 'mechanize' frame work is, that the pages I want to automate might > contain a lot of javascript for the construction of the actual page. > > Thanks in advance for any pointers ideas. I have had some good experience with Sikuli. http://sikuli.org/ Regards, Andreas bal...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter polling example: file copy with progress bar
Unfortunately you use command('cp...') to copy the file instead of Pythons portable library methods. This choice effectively makes your program work on Unix only (not Windows). See http://modcopy.sourceforge.net for a more portable version. Regards, bal...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: matplotlib / backend
On Aug 25, 10:12 am, Pierre wrote: > Hello, > > I'm to plot some results but it doesn't work. > I got this error : > > /usr/local/libre_rep/python-2.6.1/RHEL_5__x86_64/lib/python2.6/site- > packages/matplotlib/backends/__init__.py:41: UserWarning: > Your currently selected backend, 'agg' does not support show(). > Please select a GUI backend in your matplotlibrc file ('/usr/local/ > libre_rep/python-2.6.1/RHEL_5__x86_64/lib/python2.6/site-packages/ > matplotlib/mpldata/matplotlibrc') > or with matplotlib.use() > > Any idea to fix it ? > > Thanks Try: import matplotlib matplotlib.use('TkAgg') before coding anything else from the examples section of the matplotlib documentation http://matplotlib.sourceforge.net/examples/user_interfaces/embedding_in_tk.html -- http://mail.python.org/mailman/listinfo/python-list