Re: how to call a function for evry 10 secs

2011-07-01 Thread Rune Strand
from threading import Timer

def Func_to_call:
   do_stuff()

my_timer = Timer(10, Func_to_call)
my_timer.start()

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to timeout when waiting for raw_input from user ?

2009-12-07 Thread Rune Strand
On Dec 5, 3:42 pm, Maxim Khitrov mkhit...@gmail.com wrote:

 I'm not talking about the Timer, I'm talking about the original
 question. There's nothing (that I know of) you can do with a Timer on
 Windows to interrupt a raw_input call.

That is true. But if the issue here is to present a question, and
await answer for N seconds, before pusing next question, Timer() can
be used to call SendKeys() and have it send {ENTER} to raw_input.

http://www.rutherfurd.net/python/sendkeys/index.html

SendKeys is Win-only
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to timeout when waiting for raw_input from user ?

2009-12-05 Thread Rune Strand
The easiest wasy is to use the Timer object in the threading module.


from threading import Timer

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to timeout when waiting for raw_input from user ?

2009-12-05 Thread Rune Strand
On Dec 5, 3:07 pm, Maxim Khitrov mkhit...@gmail.com wrote:

 Doesn't work on Windows.

 - Max

Yes, it does. I've used it a lot, also in Py2Exe apps.  Try the
documentation example yourself

def hello():
print hello, world

t = Timer(30.0, hello)
t.start() # after 30 seconds, hello, world will be printed


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How is GUI programming in Python?

2008-04-11 Thread Rune Strand
On Apr 10, 3:54 am, Chris Stewart [EMAIL PROTECTED] wrote:
...

 Next, what would you say is the best framework I should look into?
 I'm curious to hear opinions on that.

GUI-programming in Python is a neanderthal experience. What one may
love with console scripts is turned upside-down.  Projects like Boa
Constructor seemed to be a remedy, but is not developed. The Iron-
Pythonistas has a very promising RAD GUI-tool in the IronPython -
Studio, http://www.codeplex.com/IronPythonStudio - but if you're non-
Iron, only sorrow is left - unless you fancy creating GUI in a text-
editor. Something I consider waste of life.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How is GUI programming in Python?

2008-04-11 Thread Rune Strand
On Apr 11, 8:35 pm, Steve Holden [EMAIL PROTECTED] wrote:
 wxDesigner.

Yeah, but it's like Heron of Alexandria's Aeolipile compared to the
steam engine of James Watt.

IMHO, GUI with Python is pain, pain and utter pain. Even boring and
meaningless pain.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How is GUI programming in Python?

2008-04-11 Thread Rune Strand
On Apr 12, 12:03 am, Michel Bouwmans [EMAIL PROTECTED] wrote:

 Qt Designer. And creating the GUI yourself in the text editor isn't that
 bad, plus you have much better control over it.

If you like designing isual elements in an editor, that's fine for
me!
I don't,
And as I don't do it all the time, I tend to forget constructional
details and waste life googling. So for me it's pain without
cognition. AKA waste of life.

Numerous RAD' env's, fx Delphi, suggests this kind of incredibly
boring almost pre-historic, self-pestering non-sense pain is ancient,
and I  happen to agree. It's an orthodox and monkish way of
programming. Some like it that way and that's none of my business. I
don't like it that way.

Designing GUI in a text-editor (for me) always produce a : good
enough and consumes a lot of life. The Boa constructor / Delphi way
produce what I want without _wasting life_. But Boa is too unstable,
and does not claim otherwise, and there's no descent alternative I'm
aware of.

So, GUI Python still sucks far too much. Console and web Python indeed
does not.

So if the Python Foundation arrange a Descent RAD effort, I'll
happily donate $100 for starters. I think Python should be just as
easily GUI'able as it is Console'able. Python is soon 20 years old!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ping and ARP on both Win and Linux in Python

2008-03-14 Thread Rune Strand
On Mar 13, 9:14 pm, Mauro \Baba\ Mascia [EMAIL PROTECTED] wrote:
 Hi, this is my question:

 I want to know if several switch (about 50) in a big lan are up and then
 know their MAC addresses to do a list that contains host name, ip and mac.
 I know only the range of their IP addresses (the host name it's simply
 to know using socket.gethostn.

 The first idea it's to ping all ip, parse the response and then execute
 the command arp -a and parse the response.
 However this way depends on the operating system and the ping response
 depends too from the language.

 Another way it's to open the main page of the switch and parse the HTML
 code where i can find the MAC address.
 However this way depends on the particular brand's switch.

 I know (or better i think) that there is a third way: make ping and arp
 building the packets with socket and so on (but i dont have understand
 in what way do this).

 Any suggestion?

 (i've already search in google, found many sources but a lot of them
 don't works or don't do what im trying to do...)

 Regards,
 Mauretto.

There are several Ping /ICMP implentations in Python. I did something
similar using a python ping module and parsing the arp cache. A
different approach may be to use SNMP. I believe there are Python
tools around.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if a key in a dictionary exists?

2007-03-10 Thread Rune Strand
Yes, you have name.has_key(name_key) and perhaps better, the in
operator:

if name_key in name:
   do something


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading a portion of a file

2007-03-08 Thread Rune Strand
On Mar 8, 5:12 pm, [EMAIL PROTECTED] wrote:
 I am using a script with a single file containing all data in multiple
 sections. Each section begins with #VS:CMD:command:START and ends
 with #VS:CMD:command:STOP. There is a blank line in between each
 section. I'm looking for the best way to grab one section at a time.
 Will I have to read the entire file to a string and parse it further
 or is it possible to grab the section directly when doing a read? I'm
 guessing regex is the best possible way. Any help is greatly
 appreciated.

Seems like something along these line will do:

_file_ = filepart.txt

begin_tag = '#VS:CMD:command:START'
end_tag = '#VS:CMD:command:STOP'

sections = []
new_section = []
for line in open(_file_):
line = line.strip()
if begin_tag in line:
new_section = []
elif end_tag in line:
sections.append(new_section)
else:
if line: new_section.append(line)

for s in sections: print s

If your want more control, perhaps flagging inside_section,
outside_section is an idea.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Referencing Items in a List of Tuples

2007-02-24 Thread Rune Strand
On Feb 25, 3:01 am, [EMAIL PROTECTED] wrote:
   In my case, I have a list of 9 tuples. Each tuple has 30 items. The first
 two items are 3-character strings, the remaining 28 itmes are floats.

   I want to create a new list from each tuple. But, I want the selection of
 tuples, and their assignment to the new list, to be based on the values of
 the first two items in each tuple.

   If I try, for example, writing:

 for item in mainlist:
 if mainlist[item][0] == 'eco' and mainlist[item][1] == 'con':
   ec.Append(mainlist[item][2:])

 python doesn't like a non-numeric index.


try this instead:
for item in mainlist:
 if item[0] == 'eco' and item[1] == 'con':
   ec.append(item[2:])

if you want numeric adressing, try:
for i in range(len(mainlist)):
   if mainlist[i][0] == 'eco'  etc.





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: replacing substrings within strings

2007-02-14 Thread Rune Strand
On Feb 14, 1:08 pm, amadain [EMAIL PROTECTED] wrote:
 I was wondering if there was a nicer way to swap the first 2
 characters in a string with the 4th and 5th characters other than:

 darr=list(010203040506)
 aarr=darr[:2]
 barr=darr[4:6]
 darr[:2]=barr
 darr[4:6]=aarr
 result=.join(darr)

 The above code works fine but I was wondering if anybody had another
 way of doing this?

Assuming the string length is always at least 5:

def swap(s):
return '%s%s%s%s' % (s[3:6], s[2:3], s[:2], s[6:])


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: replacing substrings within strings

2007-02-14 Thread Rune Strand
Or, slighly slower, but more general:

def swap(s, order=(3,4,2,0,1)):
# assert len(s) = len(order)
return ''.join([s[o] for o in order]) + s[6:]




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: rot13 in a more Pythonic style?

2007-02-14 Thread Rune Strand
You could try some_string.encode('rot_13')

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib2 on Windows Vista

2006-07-08 Thread Rune Strand

Sriram  Krishnan wrote:
 I'm running Python 2.4.3 on Windows Vista June CTP. I'm not able to
 open any site using the urllib2 and related family of modules

My wil guess is that it is a firewall problem. Perhaps you'll have to
specify that python.exe is trusted.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Module for creating a screenshot of a web page given a URL?

2006-07-05 Thread Rune Strand
[EMAIL PROTECTED] wrote:
 Is there a Python module that, given a URL, will grab a screenshot of
 the web page it goes to? I'd like to be able to feed such a module a
 list of URLs from a file.

 Thanks very much.

Not as I know of, but it's easy to write

Something like this quasi-code:

import time,webbrowser
from PIL import ImageGrab

list_of_urls = [''http://www.google.com', 'http://www.egg.net']

for url in list_of_urls:
 webbrowser.open(url)
 time.sleep(5)  # wait for it to load
 screen = ImageGrab.grab(coords etc)
 screen.save(some_name_in_some_path)

Untestetd, but I'm pretty sure something like this will do.
If you need more control, and on windows, try pywinauto

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: built in zip function speed

2006-07-04 Thread Rune Strand
itertools.izip is usually faster than zip. You can try that.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: built in zip function speed

2006-07-04 Thread Rune Strand

 so fastest overall

you may experience speed-ups by using

from itertools import izip

and just use izip() instead to avoid the module namespace lookup. The
same applies for the list.append() methods. If you're appending some
million times

a_list = []
a_list_append = a_list.append
a_list_append(value)

will be faster than

a_list.append(value)

but not much.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Time out question

2006-07-03 Thread Rune Strand

Grant Edwards wrote:
 I just use signal.alarm():

 import signal,sys

 def alarmHandler(signum, frame):
 raise 'Timeout'

 signal.signal(signal.SIGALRM, alarmHandler)

 while 1:
 try:
 signal.alarm(5)
 t = sys.stdin.readline()
 signal.alarm(0)
 print t
 except 'Timeout':
 print too slow
 
 -- 

Very nice, but UNIX only.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ascii character - removing chars from string

2006-07-03 Thread Rune Strand
bruce wrote:
 hi...

 i'm running into a problem where i'm seeing non-ascii chars in the parsing
 i'm doing. in looking through various docs, i can't find functions to
 remove/restrict strings to valid ascii chars.

 i'm assuming python has something like

 valid_str = strip(invalid_str)

 where 'strip' removes/strips out the invalid chars...

 any ideas/thoughts/pointers...

If you're able to define the invalid_chars, the most convenient is
probably to use the strip() method:
 a_string = abcdef
 invalid_chars = 'abc'
 a_string.strip(invalid_chars)
'def'

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner Programmer Question

2006-06-26 Thread Rune Strand

 I am doing alot of reading, and the problem didnt come with an answer.
 I dont understand how to get it to continually input numbers and add
 all those together

Use while, raw_input, sys.argv[1] and int() and break the loop when the
sum is above 100.

;-)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner Programmer Question

2006-06-26 Thread Rune Strand

[EMAIL PROTECTED] wrote:
 Rune Strand wrote:
  
   I am doing alot of reading, and the problem didnt come with an answer.
   I dont understand how to get it to continually input numbers and add
   all those together
 
  Use while, raw_input, sys.argv[1] and int() and break the loop when the
  sum is above 100.
 
  ;-)

 thanks for the help..but i am extremley new and what you said makes no
 sense to me

In the code you posted above here: Move the input into the while loop.
You may prefer raw_input() to input().

I don't want to write the code for you ;-)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tetris

2006-06-18 Thread Rune Strand

Devon G. Parks wrote:
 I've been searching google and this group for a while now for a good
 tutorial on making a Tetris-style game in Python. I hear Tetris is a
 good starting point, and although I am fairly new to programming I
 think I would learn best if I had some code to experiment with because
 without a tutorial I have no idea where to start. If you know of a
 tutorial that is specific to this game please let me know where to find
 it.

There's a 600-liners here: http://www.pygame.org/projects/21/133/

Not a tutorial, but maybe just as good?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is fun (useless social thread) ;-)

2006-06-17 Thread Rune Strand
In 2002, I was in need of a multi-platform language. My choice became
Python, in spite of friends fiercly defending Perl and some interesting
Slashdot-articles on Ruby. But back on university, I met a very, very
pretty C++ girl who said many favourable things about Python. She never
became mine, but the sympathy for Python that she implanted in my mind,
turned out to make me immune against the Perl propaganda.

So Python (for me) could be said to be either a substitute for the
prettiest of the (many) pretty girls of Norway or a mindchild of the
same.

I found a script demonstrating search/replace in files. And even if I
hadn't coded in a year, I found Python surprisingly easy to read,
understand and change. So there I was.

 Did you have to learn it for a job?

No, but I use it as often as possible in work contexts.

 Or did you just like what you saw and decided to learn it for fun?

That's more like it.

 Also, how did you go about learning it?

I ported som other scripts (Bash, PHP, and DOS bat-files) to Python
while searching the net each time I became lost. Porting is a good
learning method.

 Was there any necessity in the specifics you learned,
 or did you just dabble in something
 (e.g. wxPython) for fun?

Mostly fun and some practical problems. Later I've used Boa Constructor
to make GUI's for some customers.

 Are there still some things you feel you need to learn or improve?

Sure, I struggle with OO when it gets complicated and new features like
decorators. And idioms. But generally it's programming skills and
algorithmic scent I need.

 Additional comments/complains here:   :)

I'm a bit afraid that the new features and the turning to concepts like
iterators and generators are making Python elitistic. Old python code
floating around the net is generally easy to read, while newer often is
harder to grasp. I don't like it when my own inherent stupidity becomes
to obvious to hide.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looping through a file a block of text at a time not by line

2006-06-14 Thread Rune Strand

Rosario Morgan wrote:
 Hello

 Help is great appreciated in advance.

 I need to loop through a file 6000 bytes at a time.  I was going to
 use the following but do not know how to advance through the file 6000
 bytes at a time.

 file = open('hotels.xml')
 block = file.read(6000)
 newblock = re.sub(re.compile(r'Rate.*?/Rate'),'',block)
 print newblock

 I cannot use readlines because the file is 138MB all on one line.

 Suggestions?

 -Rosario

Probably a more terse way to do this, but this seems to work
import os

offset = 0
grab_size = 6000
file_size = os.stat('hotels.xml')[6]
f = open('hotels.xml', 'r')

while offset  file_size:
f.seek(offset)
data_block = f.read(grab_size)
offset += grab_size
print data_block
f.close()

-- 
http://mail.python.org/mailman/listinfo/python-list


Screen capturing on Windows

2006-06-13 Thread Rune Strand

Is it possible by use of pyWin32 or ctypes to make a screen capture of
an inactive, or a hidden window if the hwnd/WindowName/ClassName is
known? I've seen dedicated screen capture software do this. While
PIL.ImageGrab.grab() is excellent, it will only capture the foreground
of the desktop. I've tried for hours, but I soon get helplessly lost in
the labyrinths of the Win32API.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a string problem

2006-06-13 Thread Rune Strand

[EMAIL PROTECTED] wrote:
 hi

 if i have a some lines  like this
 a ) here is first string
 b ) here is string2
 c ) here is string3

 When i specify i only want to print the lines that contains string ie
 the first line and not the others. If i use re module, how to compile
 the expression to do this? I tried the re module and using simple
 search() and everytime it gives me all the 3 lines that have string
 in it, whereas i only need line 1.
 If re module is not needed, how can i use string manipulation to do
 this? thanks

If this is a RL-situation, 
if mystring.endswith('string') will do

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: import hook

2006-06-11 Thread Rune Strand
Jeremy Sanders wrote:
 Hi - Is it possible to override the import process so that if in my program
 I do
(...)

 Any ideas?


Why not handle the foo.bar/version string separately and just append
the resulting path to sys.path?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: John Bokma harassment

2006-05-24 Thread Rune Strand

Xah Lee wrote:
 I'm sorry to trouble everyone. But as you might know, due to my
 controversial writings and style, recently John Bokma lobbied people to
 complaint to my web hosting provider. After exchanging a few emails, my
 web hosting provider sent me a 30-day account cancellation notice last
 Friday.

[EMAIL PROTECTED]
  ∑ http://xahlee.org/

I can just declare my support. Reading Mr. Bokmas comments below [*]
certainly makes my suport stronger.

*
http://groups.google.com/group/comp.lang.python/tree/browse_frm/thread/28edb6b248dbae85/b89d934d12adf3a9?rnum=61utoken=rJk98zMqRjR_RIs2SQx_9Hh6SccKbmCj1Nw6TBD3Zp3qTOpBLP1axhNO2WH2KLoXjtKtup7b9E_jTXH5EMe8d2Tvis0T_done=%2Fgroup%2Fcomp.lang.python%2Fbrowse_frm%2Fthread%2F28edb6b248dbae85%2Fbbcab154ad579cd4%3Futoken%3DrJk98zMqRjR_RIs2SQx_9Hh6SccKbmCj1Nw6TBD3Zp3qTOpBLP1axhNO2WH2KLoXjtKtup7b9E_jTXH5EMe8d2Tvis0T%26#doc_837dc168e2a56fa2

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Is Welfare Part of Capitalism?

2006-05-09 Thread Rune Strand
Welfare is not a built-in, but in some distributions it's available as
a module. Just type import Welfare. However, be aware of the
Welfare.division() queerness. It won't be fixed until the Python 3000
is a fact. There is also some issues with the garbage collection. Under
certain circumstances the dreaded Dutch disease may occur.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Measure memory usage in Python

2006-05-01 Thread Rune Strand

gene tani wrote:
 Rune Strand wrote:
  Is there a way to measure how much memory a data structure use? For
  instance, what is the footprint of a particular list object like
  [0,1,2,3,4,5,6,7,8,9]?

 i have a note to try this, but haven't got around to it, if you want to
 blog/post

 http://pysizer.8325.org/

Thank you!  That seems to be what I was looking for.

-- 
http://mail.python.org/mailman/listinfo/python-list


Measure memory usage in Python

2006-04-30 Thread Rune Strand
Is there a way to measure how much memory a data structure use? For
instance, what is the footprint of a particular list object like
[0,1,2,3,4,5,6,7,8,9]?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to Convert a string into binary

2006-04-15 Thread Rune Strand

HNT20 wrote:
 Hello All


def ascii_to_bin(char):
ascii = ord(char)
bin = []

while (ascii  0):
if (ascii  1) == 1:
bin.append(1)
else:
bin.append(0)
ascii = ascii  1

bin.reverse()
binary = .join(bin)
zerofix = (8 - len(binary)) * '0'

return zerofix + binary



some_string = 'Time to go now, Rummy?'

binary = []
for char in some_string:
binary.append(ascii_to_bin(char))

print binary
print  .join(binary)



some_string = 'Time to go now, Rummy?'

binary = []
for char in some_string:
binary.append(ascii_to_bin(char))

print binary
print  .join(binary)


 ['01010100', '01101001', '01101101', '01100101', '0010',
'01110100', '0110', '0010', '01100111', '0110', '0010',
'01101110', '0110', '01110111', '00101100', '0010', '01010010',
'01110101', '01101101', '01101101', '0001', '0011']
01010100 01101001 01101101 01100101 0010 01110100 0110 0010
01100111 0110 0010 01101110 0110 01110111 00101100 0010
01010010 01110101 01101101 01101101 0001 0011


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how relevant is C today?

2006-04-10 Thread Rune Strand

gregarican wrote:
 1) Smalltalk - The original object oriented programming language.
 Influenced anything from Mac/Windows GUI to Java language.

No. Simula is the original object oriented programming language.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mod_python + apache + winxp = nogo

2006-04-07 Thread Rune Strand
I've set up that combo several times. I haven't had any problems. I
just looked at apach.conf, it's the same line. Did you run the
mod_python-3.2.8.win32-py2.4.exe installer?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to parse a name out of a web page?

2006-04-05 Thread Rune Strand

Haibao Tang wrote:
 with high accuracy...

 My temporary plan is to first recognized consecutive two or three
 initial-capitalized words, but certainly we need to do more than that?
 Anyone has suggestions?

 Thanks first.

It's not easy to say without seeing the HTML. If you the structure
allows it, a couple of str.split() is probably the easiest way, but you
always have BeautifulSoup.

http://www.crummy.com/software/BeautifulSoup/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to create a copy of a list

2006-04-04 Thread Rune Strand

Frank Millman wrote:
 Hi all

 Assume a 2-dimensional list called 'table' - conceptually think of it
 as rows and columns.

 Assume I want to create a temporary copy of a row called 'row',
 allowing me to modify the contents of 'row' without modifying the
 contents of 'table'.

 I used to fall into the newbie trap of 'row = table[23]', but I have
 learned my lesson by now - changing 'row' also changes 'table'.

 I have found two ways of doing it that seem to work.

 1 - row = table[23][:]

 2 - row = []
  row[:] = table[23]

 Are these effectively identical, or is there a subtle distinction which
 I should be aware of.

 I did some timing tests, and 2 is quite a bit faster if 'row'
 pre-exists and I just measure the second statement.


you could use list()

row = list(table[23])

The effect is the same, but it's nicer to read.
See also the copy module.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can I get the index number in for x in y loop?

2006-04-03 Thread Rune Strand

JuHui wrote:
  a='String'
  for x in a:
 ... print x
 ...
 S
 t
 r
 i
 n
 g
 

 can I get the index number  of a in the upon loop within for x in a
 loop?

for x, y in enumerate(a)
print x, y

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception handling....dumb question?

2006-03-31 Thread Rune Strand

kbperry wrote:
 In Python,
 When using the default except (like following)

 try:
 some code that might blow up

 except:
 print some error message


 Is there a way to show what error it is throwing?

 Like in Java, you can do
 catch (Exception e){
 System.out.println(e);
 }

 Or something like that.

 Is there an equivalent way to do this in Python?

see sys.exc_info( )

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert Word .doc to Acrobat .pdf files

2006-03-28 Thread Rune Strand

kbperry wrote:
 Questions:
 Does Acrobat Pro, have some way to interface with it command-line (I
 tried searching, but couldn't find anything)?  Is there any other good
 way to script word to pdf conversion?

 Note:  The word documents do contain images, and lots of stuff besides
 just text.

The Acrobat Distiller installs (or van install) a Word VBS macro which
allows Word to Save As .PDF. It's easy to call from Python:

doc = somefile.doc
import win32com.client

# Create COM-object
wordapp = win32com.client.gencache.EnsureDispatch(Word.Application)

wordapp.Documents.Open(doc)
wordapp.Run('!CreatePDFAndCloseDoc)  # the name of the macro for
Acrobat 6.0
wordapp.ActiveDocument.Close()
wordapp.Quit()

You'll probably wrap this in more logic, but it works.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cookbook for beginners?

2006-03-26 Thread Rune Strand

Aahz wrote:
 If you were going to name three or five essential recipes from the
 Python Cookbook suitable for beginners, what would you pick?

 Yes, this is for _Python for Dummies_, so idioms that aren't in the
 Cookbook are also fine.

If it's for _beginners_ / _dummies_, I would expect things like

1.6
names = ['George', 'Saddam', 'Osama']
name_string = ', '.join(names)

4.10
dict.setdefault(k, v)

?.?
dict = dict(zip(list_a, list_b))

- listcomps

2.1 / 2.2
reading/writing from/to files

?.?
string-methods like .split(), .upper(), endswith(), startswith(),
isalpha() ...

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MVC in Python for web app dev

2006-03-25 Thread Rune Strand

[EMAIL PROTECTED] wrote:
 Please let me state off the cuff that I'm not after a big Python Vs
 Ruby war or anything here! I'm trying to make the switch to Python for
 my web development work as I've been using it for quite some time for
 other programming work (albeit mainly hobby and personal interest
 projects) as I'm getting to the stage where the need for a real MVC
 capable language framework is a must simply to save some time and PHP
 just isn't cutting it (although CakePHP is all right and the new Zend
 framework looks to hold some promise).

 Here's where I'm in a pickle! I would prefer to stick with Python as I
 am enjoying it BUT Ruby on Rails is simply too hard to deny a look in.
 The ease that it provides in generating scaffolding and the intuitive
 templating engine is just plain good, adding in to this the RadRails
 Eclipse plugin for a beautiful IDE (I know, I know how great
 vim/emacs/whatever is but still, if RadRails is going to save some time
 frankly I'm liking it already!). I'm aware that Pylons is trying to
 compete with Rails in the near future but I'm just not clear on how
 directly they are trying to compete...will Pylons have the same
 generation functions and other time saving goodies that RoR has or am I
 barking up the wrong tree?

 Basically I'm not going to abandon Python because I find it fits me
 better as a language than Ruby, but when I need to be able to develop
 good, stable MVC web apps in a small amount of time I don't want to be
 wasting my time waiting for Python to deliver something it's just not
 going to (I also forgot to mention I don't want to run on a custom
 little webserver, I prefer the piece of mind I have with Apache - in
 true LAMP style :P).

 So I'm asking for ANY opinions here! For datadriven web apps that need
 to be able to support small and large scale distros, can Python deliver
 or is RoR the way to go?

 Thanks for any help you guys throw at me!! Oh, and any examples like
 current big webapps to back up a particular point of view would be
 greatly appreciated too! Thanks!


http://www.djangoproject.com/
http://www.turbogears.org/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding a __filename__ predefined attribute to 2.5?

2005-10-13 Thread Rune Strand
I've read a lot of your comments the last years. Your friendliness
always strikes me.

-- 
http://mail.python.org/mailman/listinfo/python-list


Adding a __filename__ predefined attribute to 2.5?

2005-10-12 Thread Rune Strand
Is it an idea to include a new __filename__ predefined attribute to
2.5, so that __file__ contains the entire path to the module, and
__filename__ only the name of the module?

For instance it's useful to include a not-static reference to the
filename in a scripts usage() section and it's cumbersome to extract
the filename or to do module imports just to parse it.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding a __filename__ predefined attribute to 2.5?

2005-10-12 Thread Rune Strand
I Steve,

I know it's several ways to isolate the filename. I just want to avoid
the overhead of importing sys or os  to achieve it.

Currently I have this in my scripts:
__filename__ = __file__.replace('\\', '/').rsplit('/', 1)[-1]

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding a __filename__ predefined attribute to 2.5?

2005-10-12 Thread Rune Strand
Excuse me, do you suffer from a bad hair-day? I didn't say it is
platform independant. It's ok for my use on Linux and Windows. If you
cannot imagine any other usecase for a __filename__ attribute, that's
your problem, not mine.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding a __filename__ predefined attribute to 2.5?

2005-10-12 Thread Rune Strand
 those modules are already imported when Python gets to your code, so
 the only overhead you're saving is a little typing.

I don't understand this. Could you please elaborate?  - if sys or os
are not imported for any other causes how are they already imported?
Maybe I'm wrong here, and accessing the filesystem and reading the
module into memory represents no cost. My mistake, in that case.

 wow.  that's one lousy optimization...

 here's a *shorter* piece of code, which is also readable and portable, and
 a lot easier to type on most keyboards:

   import os
  __filename__ = os.path.basename(__file__)

It may be lousy, but it requires no imports. And, as I said in the
answer to Steve, I _know_ there are many ways to achieve this,
including yours. But in your rush to pin-point lousy code, you didn't
read that, I suppose.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding a __filename__ predefined attribute to 2.5?

2005-10-12 Thread Rune Strand
Ok, Alex. I know a good explanation when I see one. Thanks!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: week-year conversion to date

2005-09-14 Thread Rune Strand

year = '2005'
week = 50
weekday = 1 # Monday is 1

time_expr = '%s, %s, %s' % (year, week, weekday)
time_struct = time.strptime(time_expr, %Y, %W, %w)
print time.strftime(%Y%m%d, time_struct)

But the datetime module may have an easier way

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Some advice on startingout with python.

2005-09-14 Thread Rune Strand
It's not about GUI, but it's a good book. It's both online and printed:

http://diveIntoPython.org

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: execute commands independantly

2005-09-06 Thread Rune Strand

Mike Tammerman wrote:
 I am trying to execute an executable or a pyton script inside my
 program. I looked at the subprocess and os module. But all the
 functions in these modules blocks my application. What I want to do is
 run the subprocess without any concern. I don't care of its return type
 or child signals. Just start and let it run independantly.

If you don't need any output, os.system('app') should do.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File parser

2005-08-29 Thread Rune Strand
It's not clear to me from your posting what possible order the tags may
be inn. Assuming you will always END a section before beginning an new,
eg.

it's always:

A
 some A-section lines.
END A

B
some B-section lines.
END B

etc.

And never:

A
 some A-section lines.
B
some B-section lines.
END B
END A

etc.

is should be fairly simple. And if the file is several GB, your ought
to use a generator in order to overcome the memory problem.

Something like this:


def make_tag_lookup(begin_tags):
  # create a dict with each {begin_tag : end_tag}
  end_tags = [('END ' + begin_tag) for begin_tag in begin_tags]
  return dict(zip(begin_tags, end_tags))


def return_sections(filepath, lookup):
  # Generator returning each section

  inside_section = False

  for line in open(filepath, 'r').readlines():
line = line.strip()
if not inside_section:
  if line in lookup:
inside_section = True
data_section = []
section_end_tag = lookup[line]
section_begin_tag = line
data_section.append(line) # store section start tag
else:
  if line == section_end_tag:
data_section.append(line) # store section end tag
inside_section = False
yield data_section # yield entire section

  else:
data_section.append(line) #store each line within section


# create the generator yielding each section
#
sections = return_sections(datafile,
make_tag_lookup(list_of_begin_tags))

for section in sections:
  for line in section:
print line
  print '\n'

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find Windows Application data directory??

2005-06-28 Thread Rune Strand
You have the environment variable APPDATA. You can access it with
os.environ().

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Better console for Windows?

2005-06-27 Thread Rune Strand
Brett Hoerner wrote:

 Another problem with cmd.com is when I run IPython, if I have an error,
 or tab or anything, I get the speaker beep (ala linux) but I can't find
 a way to turn it off.  This is a huge problem because I cannot disable
 my system speaker on my laptop (not even in BIOS like my old one, and
 it's an error, it bypasses the fact that all my sound is muted in
 Windows) and I get incredibly loud beeps all the time (because I suck)
 which would not be acceptable while I'm coding on the sly in boring
 class.

I know that problem... it's extremely annoying!
Here's one way to solve it;

1. Start 'Device manager'.
2. On the menu, click 'View' and check off Show hidden devices
3. Locate 'Beep' 'under Non-Plug and Play Drivers'
4. Right-click 'Beep', select 'Disable'

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Better console for Windows?

2005-06-27 Thread Rune Strand

Annoyed by windows? Check this URL:
http://www.annoyances.org/exec/show/category01

;-)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which kid's beginners programming - Python or Forth?

2005-06-27 Thread Rune Strand


BORT wrote:
 Please forgive me if this is TOO newbie-ish.

 I am toying with the idea of teaching my ten year old a little about
 programming.  I started my search with something like best FREE
 programming language for kids.  After MUCH clicking and high-level
 scanning, I am looking at Python and Forth.  Both have advocates that
 say each is a great approach to learning computers.


You may find RUR interesting
http://rur-ple.sourceforge.net/
(Learning Python: Child's Play with RUR-PLE!)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading a list from a file

2005-06-20 Thread Rune Strand
But iif it are many lists in the file and they're organised like this:

['a','b','c','d','e']
['a','b','c','d','e']
['A','B','C','D','E'] ['X','F','R','E','Q']

I think this'll do it

data = open('the_file', 'r').read().split(']')

lists = []
for el in data:
el = el.replace('[', '').strip()
el = el.replace(', )
lists.append(el.split(','))

# further processing of lists

but the type problem is still to be resolved ;-)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading a list from a file

2005-06-20 Thread Rune Strand
:-/  You're right!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: windows directory

2005-06-14 Thread Rune Strand
On XP at least you have the environment variable ProgramFiles.

You can fetch the path it holds through os.environ

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to operate the excel by python?

2005-06-11 Thread Rune Strand
John,

I wrote a script that autmates the conversion from XLS to CSV. It's
easy. But your points are still good. Thanks for making me aware the
xlrd module!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to operate the excel by python?

2005-06-09 Thread Rune Strand
The key is Python for Windows :
http://starship.python.net/crew/mhammond/win32/

See here for an Excel dispatch example:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325735

When doing such operations, I generally save all the Excel files to CSV
files and do the operations on them using the csv module.

-- 
http://mail.python.org/mailman/listinfo/python-list


Strange KeyError using cPickle

2005-06-01 Thread Rune Strand
I'm experiencing strange errors both with pickle and cPickle in the
below code:


import cPickle as pickle
#import pickle
from string import ascii_uppercase
from string import ascii_lowercase

def createData():
d1 = list(Something's rotten)
d2 = tuple('in the state of Denmark')

d3 = [('a', 'b'), ('c', 'd')]
#d3 = [('s a', 's b'), ('s c', 's d')]
#d3 = [('sa', 'sb'), ('sc', 'sd')]
#d3 = [['s a', 's b'], ['s c', 's d']]

d4 = dict(zip(ascii_uppercase,ascii_lowercase))
return [d1, d2, d3, d4]

def doPickle(data, pickleFile = 'pickleTest.p', proto = 2):
f = XWwz(pickleFile, 'w')
p = pickle.Pickler(f, proto)
p.dump(data)
f.close()

def doUnpicle(pickleFile = 'pickleTest.p'):
f = XWwz(pickleFile, 'rb')
up = pickle.Unpickler(f)
data = up.load()
f.close()
return data

data = createData()
doPickle(data)
xdata = doUnpicle()


1) The above code works, but if I use pickle instead of cPickle, I get
   KeyError: '\n' when unpickling.

2) If I uncomment any of the other d3 bindings in createData(), I get
   KeyError: '\n', or
   cPickle.UnpicklingError: invalid load key, '' (newline)

3) If I don't use the d1, d2 and d4 bindings, no error occurs.

I can't find the explanation. Why the newline error? There are no
newlines in the data. Are not all those structures pickable?

Thanks for all help!

(on WinXP, CPython 2.4.1)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange KeyError using cPickle

2005-06-01 Thread Rune Strand
[Tim Peters]
 What is XWwz?  Assuming it's a bizarre typo for open, change the
 'w' there to 'wb'.  Pickles are binary data, and files holding pickles
 must be opened in binary mode, especially since:

  ...
  (on WinXP, CPython 2.4.1)

Thanks Tim. The bizarre 'typo' appears to be caused by ad-blocking
software confusing python code with javascript (i think).

I had the feeling this was a red facer.

Setting the protocol to 0 (text) also  make it work.

-- 
http://mail.python.org/mailman/listinfo/python-list


Python as client-side browser script language

2005-05-31 Thread Rune Strand
What would it take to create a Firefox extension that enables Python as
a script language in the browser - just like Javascript? Is it at all
possible? Are the hundred good reasons not to bother?

I once made an application that used MozPython[1]. It was fun and very
fast compared to the Mod_Python I eventually replaced it with. I had
to, because of all the mess updating Mozilla caused. ActiveState has a
project too [2]. But none of these can replace Javascript

Grail used Python as scrpt language, I believe. And by the
Win32-wonders of Mr. Hammeond it's possible to use Python in IE. But
what aboit a easy-to-install extension for Firefox? Wouldn't that be
cool?


[1] http://www.thomas-schilz.de/MozPython/README.html
[2] http://www.mozilla.org/catalog/architecture/xpcom/pyxpcom/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: speeding up Python script

2005-05-17 Thread Rune Strand
Without seeing any code, it's hard to tell, but it's not a wild guess
that 'six inside for loops' may be replaced by more efficient ways ;-)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unique Elements in a List

2005-05-09 Thread Rune Strand
You're right. I somehow missed the index part :-o. It's easy to fix
though.

-- 
http://mail.python.org/mailman/listinfo/python-list