Re: Numpy on 2.7

2010-09-20 Thread Pekka Niiranen

On 9/20/10 2:36 PM, Dirk Nachbar wrote:

I am trying to install Numpy on Python 2.7 but it only looks for 2.6
folder, how can I change that?

Dirk

http://sourceforge.net/projects/numpy/files/NumPy/1.5.0/numpy-1.5.0-win32-superpack-python2.7.exe/download

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


Daylight saving time question

2007-03-20 Thread Mr Pekka Niiranen
Hi,

is it possible to get the two annual daylight saving times
(day, month and time) from Python by giving location
in some country/location string (Europe/Finland for example).

I need to ask country in program and calculate daylight
saving times for the next few years onwards somehow like this:

for y in range(2007, 2017):
(m1,d1,t1,m2,d2,t2) = daylight_change_epochs(Finland)

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


Re: serial ports, threads and windows

2006-08-03 Thread Pekka Niiranen
Tom Brown wrote:
 Hey people,
 
 I've written a python app that r/w eight serial ports to control eight 
 devices 
 using eight threads. This all works very nicely in Linux. I even put a GUI on 
 it using PyQt4. Still works nicely. 
 
 Then I put the app on on a virtual Windows machine running inside of vmware 
 on 
 the same Linux box.  Vmware only lets me have four serial ports so I run the 
 app against four serial ports using four threads. The app did not respond 
 quick enough to data from the serial ports and eventually hung.
 
 So, I tried one serial port and the app still did not respond quick enough to 
 the single serial port. It eventually hangs.
 
 When the app hung, in each case, it was not hogging the cpu nor reading any 
 data off the serial ports. The task manager didn't show it was doing anything 
 at all.
 
 When it runs on Windows, could it be:
 
 1) Just struggling to run inside of VMware?
 
 2) Using threads with Qt on Windows is a problem?
 
 3) Threads in python on Windows is a problem?
 
 Any ideas?
 
 Thanks,
 Tom

Hi,

I have been using wxpython myself with pyserial in Windows 2000/XP.
No problems. Below are (edited) code segments. The self.jam is
used for stopping serial port processing without stopping the thread.

 thread example starts 

class T1Thread(Thread):
 def __init__(self, inport):
 Thread.__init__(self)
 self._want_abort = 0
 self.inprt = inport# COMx
 self.inprt.flushInput()
 self.run_count = 0
#
 self.jam = false
#
 self.start()

 def run(self):
 while self._want_abort == 0:
 if not self.jam:
 self.read_simulations()
 sleep(1)

 def abort(self):
 self._want_abort = 1   # Stop from GUI


 def read_simulations(self):
..blah..blah..
self.inprt.flushInput()
sleep(5)

 thread example ends 

 Wxpython code starts 

 def OnRun(self, event):
 if self.in_port != No and not self.T1worker:
 self.T1worker = T1Thread(self.inprt)
 if self.out_port != No and not self.T2worker:
 self.T2worker = T2Thread(self.outprt)
 if self.in2_port != No and not self.T3worker:
 self.T3worker = T3Thread(self.in2prt)


 def OnStop(self, event):
 if self.T1worker:
 self.T1worker.abort()
 if self.T2worker:
 self.T2worker.abort()
 if self.T3worker:
 self.T3worker.abort()
 sleep(3)
 self.T1worker= None
 self.T2worker= None
 self.T3worker= None
 print \nSTOPPED\n

 Wxpython code ends 

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


Re: Python 2.5 Schedule

2006-03-19 Thread Pekka Niiranen
Hi,

what I would like to see in (www.python.org) is
Windows installation package (*.msi)
compiled with option --enable-unicode=ucs4.
See http://www.xml.com/pub/a/2005/06/15/py-xml.html

-pekka-

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


Re: SOLVED: Help needed: file writing problem with subprocess

2005-12-05 Thread pekka niiranen
Fredrik Lundh wrote:
 Pekka Niiranen wrote:
 
 
I am running Python script in W2K or in WinXP.
The script is started from DOS prompt and writes text file to disk
with codecs.open() in UTF8.

The problem is: When script writes the file and tries to read it
with by calling itself thru subprocess() the created files are
NOT accessible because they have not been written into disk yet.
fh.flush() and os.fsync() do not work.

-- extract from myscript.py starts --

fh = codecs.open(myfile.txt, w, utf8)
fh.write(# Comment line\n)
fh.writelines(some list)
fh.flush()
fh.close()

then later:

mycmd = %s -f %s % (myscript.py, myfile.txt)
subprocess.call(mycmd, shell=True)

This fails: myfile.txt is not yet written into disk
and the myscript.py called thru subprocess fails.
Only after the main script exits will myfile.txt occur
into the directory.
 
 
 this should of course work, and it sure works for me.
 
 does this involve any unconventional file systems?  (file servers etc).
 
 how much later is later ?
 
 have you checked what the current directory is in all three cases?  (before
 you create the file, before you call the script, and before you try to open 
 the
 file in the script).
 
 /F
 
 
 
The problem was that full pathname to mytext.txt -file was wrong and my
handmade error message about it was misleading. Furthermore, Windows
Explorer showed created file on screen after considerable delay
(5sec) which made me think file was never created. Seems, that due to
operating system delays one cannot rely on his own eyes about
files true existence during script run.

Just one question more; how can I spawn/open another Dos -window
with subprocess()?

Thanks anyways,

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


Help needed: file writing problem with subprocess

2005-12-04 Thread Pekka Niiranen
Hi,

I am running Python script in W2K or in WinXP.
The script is started from DOS prompt and writes text file to disk
with codecs.open() in UTF8.

The problem is: When script writes the file and tries to read it
with by calling itself thru subprocess() the created files are
NOT accessible because they have not been written into disk yet.
fh.flush() and os.fsync() do not work.

-- extract from myscript.py starts --

fh = codecs.open(myfile.txt, w, utf8)
fh.write(# Comment line\n)
fh.writelines(some list)
fh.flush()
fh.close()

then later:

mycmd = %s -f %s % (myscript.py, myfile.txt)
subprocess.call(mycmd, shell=True)

This fails: myfile.txt is not yet written into disk
and the myscript.py called thru subprocess fails.
Only after the main script exits will myfile.txt occur
into the directory.

Previously I had Perl script calling shell script
thru system -command. My plan is to rewrite everything with Python.

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


Question about namespaces and import. How to avoid calling os.system

2005-07-22 Thread Pekka Niiranen
Hi there,

I have two scripts. The first main.py sets some variables
and then imports another called gen.py. The idea is to
provide main.py that defines some paths, variables etc.
without using Windows environment variables. Various other hackers
will make additional Python scripts (subroutines) like gen.py
that utilize variables set by the main.py and which main.py calls.
I can do this with subprocess module by setting its env -variable
but I try to avoid calling shell. How can I merge temporary
the namespaces of the two modules?

- example run STARTS ---
c:\home\pekkamain.py

imported module: module 'gen' from 'c:\home\gen.py'
{'todir': 'c:\\'}
Traceback (most recent call last):
   File C:\home\pekka\main.py, line 16, in ?
 gencmd.run_gen()
   File c:\home\gen.py, line 7, in run_gen
 print env_params  # HOW MAKE THIS DICTIONARY FROM main.py VISIBLE
NameError: global name 'env_params' is not defined

- example run STOPS ---

 main.py STARTS 
import os, sys
env_params = {}
env_params['EDITOR'] = foo

def import_libs(dir, script):
  Imports python script
 sys.path.insert(0,(os.path.normpath(dir)))
 module_name, ext = os.path.splitext(script)
 my_script = __import__(module_name)
 print \nimported module: %s % (my_script)
 del sys.path[0]
 return my_script

if __name__ == __main__:
 gencmd = import_libs(c:\home, gen.py)
 gencmd.run_gen()

---main.py ENDS -

 gen.py STARTS 
# Store this script to directory c:\home
my_env_params ={}
my_env_params['todir'] = c:\\

def run_gen():
 # Get commandline arguments
 print my_env_params
 print env_params  # HOW MAKE THIS DICTIONARY FROM main.py VISIBLE

if __name__ == __main__:
 run_gen()

---gen.py ENDS -


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


Re: Question about namespaces and import. How to avoid calling os.system

2005-07-22 Thread Pekka Niiranen
Thanks,

I will analyse these 4 options and select the most suitable
since there are other issues involved too, like
the main.py reads contents of a file to a list that gets
passed to the gen.py with dictionary env_params.
I try to avoid parsing the contents of the file both
in main.py and in gen.py

-pekka-

  Jeff Epler wrote:

 In main.py, execfile(gen.py)
 
 or
 
 In gen.py, have something like
 from __main__ import env_params
 
 or
 
 In main.py, have something like
 import __builtins__; __builtins__.env_params = env_params
 
 or
 
 call a function in the gen.py with env_params as a parameter
 import gen
 gen.do(env_params)
 
 Jeff
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HELP: Python equivalent of UNIX command touch

2005-03-02 Thread pekka niiranen
Roy Smith wrote:
pekka niiranen  [EMAIL PROTECTED] wrote:
Does anybody know Python recipe for changing the date
of the directory or files in W2K to current date and time?
In UNIX shell command touch does it.

You want os.utime()
Nope, it does not work for directories in Windows
--
http://mail.python.org/mailman/listinfo/python-list


HELP: Python equivalent of UNIX command touch

2005-02-28 Thread pekka niiranen
Does anybody know Python recipe for changing the date
of the directory or files in W2K to current date and time?
In UNIX shell command touch does it.
-pekka-
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is this a bug? BOM decoded with UTF8

2005-02-11 Thread pekka niiranen
pekka niiranen wrote:
I have two files my.utf8 and my.utf16 which
both contain BOM and two a characters.
Contents of my.utf8 in HEX:
EFBBBF6161
Contents of my.utf16 in HEX:
FEFF6161

This is not true: this byte string does not denote
two a characters. Instead, it is a single character
U+6161.
Correct, I used hexeditor to create those files.
Is there a trick to read UTF8 encoded file with BOM not decoded?

It's very easy: just drop the first character if it is the BOM.
I know its easy (string.replace()) but why does UTF-16 do
it on its own then? Is that according to Unicode standard or just
Python convention?
The UTF-8 codec will never do this on its own.

Never? Hmm, so that is not going to change in future versions?
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Is this a bug? BOM decoded with UTF8

2005-02-10 Thread pekka niiranen
Hi there,
I have two files my.utf8 and my.utf16 which
both contain BOM and two a characters.
Contents of my.utf8 in HEX:
EFBBBF6161
Contents of my.utf16 in HEX:
FEFF6161
For some reason Python2.4 decodes the BOM for UTF8
but not for UTF16. See below:
 fh = codecs.open(my.uft8, rb, utf8)
 fh.readlines()
[u'\ufeffaa']   # BOM is decoded, why
 fh.close()
 fh = codecs.open(my.utf16, rb, utf16)
 fh.readlines()
[u'\u6161'] # No BOM here
 fh.close()
Is there a trick to read UTF8 encoded file with BOM not decoded?
-pekka-
--
http://mail.python.org/mailman/listinfo/python-list


Re: goto, cls, wait commands

2005-02-10 Thread Pekka Niiranen
import os
if os.name == nt:   
os.system(cls)  # Works in w2k
else:
os.system(clear)# Works in cygwin's Bash
Ulf Göransson wrote:
Bruno Desthuilliers wrote:
Duncan Booth a écrit :
BOOGIEMAN wrote:
Secondly, how do I clear screen (cls) from text and other
content ?

That depends on your computer, and how you are running your program.
One way which *might* work is:
   import os
   os.system(cls)

*might* work... !-)
 [EMAIL PROTECTED] modulix $ cls
-bash: cls: command not found
Bad luck ! didn't work !-)

Works for me! But then again...
kairos:ug cat cls
#! /usr/local/bin/python
print \xc,
/ug 8-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: HELP: Tkinter idiom needed: SOLUTION

2005-01-03 Thread Pekka Niiranen
Hi there,
got it. Note the root.distroy()-command.
-pekka-
- CODE STARTS 
from Tkinter import *
from ScrolledText import ScrolledText
import tkFont
class Message_box:
# Graphical message box for printing unicode texts
def __init__(self, myParent):
self.myContainer1 = Frame(myParent)
self.myContainer1.pack(side=TOP, expand=1, fill=BOTH)
self.button1 = Button(self.myContainer1)
self.button1[text]= Close
self.button1.pack(side=BOTTOM)
self.button1.bind(Button-1, self.button1Click)
self.font = tkFont.Font(family=Arial Unicode MS, size=8)
self.text = ScrolledText(self.myContainer1, font=self.font,\
 state=NORMAL, height=40, width=120, wrap=NONE)
self.text.pack(side=TOP, expand=1, fill=BOTH)
def button1Click(self, event):
self.myContainer1.quit()
def write(self,s):
self.text.insert(END, s)
def enable_write(self):
self.text.config(state=NORMAL)
def disable_write(self):
self.text.config(state=DISABLED)
if __name__ == '__main__':
# first window
root = Tk()
print blah1
root.title(' Message window')
root.protocol(WM_DELETE_WINDOW, NONE)
widget = Message_box(root)
m = blah2
widget.write(%s\n % m)
widget.disable_write()  
root.mainloop()
root.destroy()
print blah3
# second window
root = Tk()
root.title(' Message window')
root.protocol(WM_DELETE_WINDOW, NONE)
widget = Message_box(root)
m = blah4
widget.write(%s\n % m)
widget.disable_write()  
root.mainloop()
root.destroy()
print blah5
- CODE ENDS 
Pekka Niiranen wrote:
Hi there,
after reading TkInter/thread -recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965
I wondered if it was possible to avoid using threads
for the following problem:
I have script started from W2K console that normally
prints ascii messages to the screen. However, I have
command line debug -flag that might cause printing
of UTF-8 data to the screen. This fails occassionally
due to Console encoding, of course.
What I need is Tkinter window where some printouts
are directed when script is run in Debug -mode
(Redirection of stdout is out of question).
While testing, I have got this far already:
---script starts
from Tkinter import *
from ScrolledText import ScrolledText
import os, sys, tkFont, codecs
class Pyg_message_box:
  def __init__(self, parent):
self.myParent = parent
self.myContainer1 = Frame(parent)
self.myContainer1.option_add(*font,\
tkFont.Font(family=Arial Unicode MS, size=8))
self.myContainer1.pack()
self.text = ScrolledText()
self.text.pack()
self.button1 = Button(self.myContainer1, text=Quit,\
 command=self.button1Click)
self.button1.pack(side=LEFT)
self.button1.bind(Button-1, self.button1Click)
  def button1Click(self, event):
 self.myContainer1.quit()
  def write(self, s):
self.text.insert(END, s)
root = Tk()
widget = Pyg_message_box(root)
sys.stdout = widget
a = codecs.open(d:\\test.txt, r, utf_16).readlines()
for x in a:
  print x
root.mainloop()
---script ends
My questions are:
- Can I open Tk -window without enclosing the whole script
  between root=Tk() and root.mainloop()?
- What is the idiom of opening Tk -window only when Debug -flag
  is encountered (the script stops running until window is closed)?
Something like:
if not my_debug == ON:
print message # prints to console
else:
# 1) open temporary ScrolledText() Tk -window
# 2) Print stuff to window
# 3) Ask user to close window
I would no like to always open Tkwindows just in case user runs script
with debug -flag on.
-pekka-
--
http://mail.python.org/mailman/listinfo/python-list


HELP: Tkinter idiom needed

2005-01-01 Thread Pekka Niiranen
Hi there,
after reading TkInter/thread -recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965
I wondered if it was possible to avoid using threads
for the following problem:
I have script started from W2K console that normally
prints ascii messages to the screen. However, I have
command line debug -flag that might cause printing
of UTF-8 data to the screen. This fails occassionally
due to Console encoding, of course.
What I need is Tkinter window where some printouts
are directed when script is run in Debug -mode
(Redirection of stdout is out of question).
While testing, I have got this far already:
---script starts
from Tkinter import *
from ScrolledText import ScrolledText
import os, sys, tkFont, codecs
class Pyg_message_box:
  def __init__(self, parent):
self.myParent = parent
self.myContainer1 = Frame(parent)
self.myContainer1.option_add(*font,\
tkFont.Font(family=Arial Unicode MS, size=8))
self.myContainer1.pack()
self.text = ScrolledText()
self.text.pack()
self.button1 = Button(self.myContainer1, text=Quit,\
 command=self.button1Click)
self.button1.pack(side=LEFT)
self.button1.bind(Button-1, self.button1Click)
  def button1Click(self, event):
 self.myContainer1.quit()
  def write(self, s):
self.text.insert(END, s)
root = Tk()
widget = Pyg_message_box(root)
sys.stdout = widget
a = codecs.open(d:\\test.txt, r, utf_16).readlines()
for x in a:
  print x
root.mainloop()
---script ends
My questions are:
- Can I open Tk -window without enclosing the whole script
  between root=Tk() and root.mainloop()?
- What is the idiom of opening Tk -window only when Debug -flag
  is encountered (the script stops running until window is closed)?
Something like:
if not my_debug == ON:
print message # prints to console
else:
# 1) open temporary ScrolledText() Tk -window
# 2) Print stuff to window
# 3) Ask user to close window
I would no like to always open Tkwindows just in case user runs script
with debug -flag on.
-pekka-
--
http://mail.python.org/mailman/listinfo/python-list


Re: what would you like to see in a 2nd edition Nutshell? A: Unicode aware scrollable message box in Tk

2004-12-31 Thread Pekka Niiranen
Well,
I have not read the previous version, but
I would like to see an example how to redirect console messages
from scripts to Tk windows in UTF-8/16 for debugging purposes.
(I hate those ordinal not in range(128) messages)
This involves setting font (Arial MS Unicode), scrollbar and
Continue -button (allows script to continue execution).
It could be called Unicode aware scrollable message box in Tk
-pekka-
Alex Martelli wrote:
I'm considering proposing to O'Reilly a 2nd edition of Python in a
Nutshell, that I'd write in 2005, essentially to cover Python 2.3 and
2.4 (the current 1st edition only covers Python up to 2.2).
What I have in mind is not as complete a rewrite as for the 2nd vs 1st
edition of the Cookbook -- Python hasn't changed drastically between 2.2
and 2.4, just incrementally.  Language and built-ins additions I'd of
course cover -- decorators, custom descriptors (already in 2.2 but not
well covered in the 1st edition), importing from zipfiles, extended
slicing of built-in sequences, sets, genexps, ... and also major new
standard library modules such as (in no special order) optparse,
tarfile, bsddb's new stuff, logging, Decimal, cookielib, datetime,
email... and new capabilities of existing modules, such as thread-local
storage.  Outside of the standard library, I was thinking of expanding
the coverage of Twisted and adding just a few things (numarray --
perhaps premature to have it _instead_ of Numeric, though; dateutils,
paramiko, py2app...).  Since the book's size can't change much, I'll
also have to snip some stuff (the pre-email ways to deal with mail, for
example; modules asyncore and asynchat, probably) to make space for all
of the additions.
I haven't take any real decisions about it, yet, except one: I'll keep
covering Tkinter, rather than moving to, say, wxPython (no space to
_add_ wx coverage while leaving Tk intact - having to choose, I still
believe Tkinter coverage is going to help more readers).  Just about
everything else is still to be finalized in my mind...
So, if there's any advice or request about a 2nd edition of the
Nutshell, this is the right time for y'all to let me know.  Feedback is
welcome, either privately or right here.  Thanks in advance -- _and_
apologies in advance because I know I just won't be able to accomodate
all the requests/advice, given the constraints on book size c.
Alex
--
http://mail.python.org/mailman/listinfo/python-list


Re: File locking is impossible in Windows? SOLUTION

2004-12-22 Thread Pekka Niiranen
Hi everybody:
I played with the class Flock and changed the line
win32con.FILE_SHARE_READ|win32con.FILE_SHARE_WRITE,\
to
win32con.FILE_SHARE_READ,\
and now I cannot copy the file over which suits me.
When file is NOT locked I get:
E:\copy d:\log.txt .
Overwrite .\log.txt? (Yes/No/All): y
1 file(s) copied.
When file IS locked I get:
E:\copy d:\log.txt .
The process cannot access the file because it is being used by another 
process.
0 file(s) copied.

Below is the new script completely. Note that when
upgrading to Python v2.4 I had to change self.highbits
from 0x to -0x7fff.
-SCRIPT STARTS
import win32file
import win32con
import win32security
import pywintypes
class Flock:
   def __init__(self,file):
self.file=file
secur_att = win32security.SECURITY_ATTRIBUTES()
secur_att.Initialize()
self.highbits=-0x7fff
self.hfile=win32file.CreateFile( self.file,\
win32con.GENERIC_READ|win32con.GENERIC_WRITE,\
win32con.FILE_SHARE_READ,\  
secur_att,\
win32con.OPEN_ALWAYS,\
win32con.FILE_ATTRIBUTE_NORMAL , 0)
   def lock(self):
lock_flags=win32con.LOCKFILE_EXCLUSIVE_LOCK|\
win32con.LOCKFILE_FAIL_IMMEDIATELY
self.ov=pywintypes.OVERLAPPED()
win32file.LockFileEx(self.hfile,lock_flags,0,\
self.highbits,self.ov)
   def unlock(self):
win32file.UnlockFileEx(self.hfile,0,\
self.highbits,self.ov)
self.hfile.Close()
if __name__ == '__main__':
import sys
l=Flock(e:log.txt)
print 'calling lock'
l.lock()
print Now locked.  Hit enter to release lock.
dummy = sys.stdin.readline()
l.unlock()
print 'now unlocked'
-SCRIPT ENDS
-pekka-
Pekka Niiranen wrote:
Hi,
I have used the following example from win32 extensions:
-SCRIPT STARTS
import win32file
import win32con
import win32security
import pywintypes
class Flock:
def __init__(self,file):
self.file=file
secur_att = win32security.SECURITY_ATTRIBUTES()
secur_att.Initialize()
self.highbits=-0x7fff
self.hfile=win32file.CreateFile( self.file,\
win32con.GENERIC_READ|win32con.GENERIC_WRITE,\
win32con.FILE_SHARE_READ|win32con.FILE_SHARE_WRITE,\
secur_att, win32con.OPEN_ALWAYS,\
win32con.FILE_ATTRIBUTE_NORMAL , 0 )
def lock(self):
lock_flags=win32con.LOCKFILE_EXCLUSIVE_LOCK|\
win32con.LOCKFILE_FAIL_IMMEDIATELY
self.ov=pywintypes.OVERLAPPED()
win32file.LockFileEx(self.hfile,lock_flags,0,\
self.highbits,self.ov)
def unlock(self):
win32file.UnlockFileEx(self.hfile,0,\
self.highbits,self.ov)
self.hfile.Close()
if __name__ == '__main__':
from time import time, strftime, localtime
import sys

l=Flock(e:log.txt)
print 'calling lock'
l.lock()
print Now locked.  Hit enter to release lock.
dummy = sys.stdin.readline()

l.unlock()
print 'now unlocked'
-SCRIPT ENDS
If I start one python process from dos window I get message:
E:\python lockker.py
calling lock
Now locked.  Hit enter to release lock.
All well, now if
1)I start another Dos -shell and run the same command I get:
E:\python lockker.py
calling lock
Traceback (most recent call last):
  File lockker.py, line 35, in ?
l.lock()
  File lockker.py, line 23, in lock
   win32file.LockFileEx(self.hfile,lock_flags,0,\
   self.highbits,self.ov)
pywintypes.error: (33, 'LockFileEx',\
'The process cannot access the file because\
 another process has locked a portion of  the file.')
Which is correct.
2)I try to read the contents of the file from Dos -shell, I get:
E:\type log.txt
The process cannot access the file because another\
process has locked a portion of the file.

This is correct.

3)When I open the file into notepad.exe I can edit the screen
but not write changes to disk. Correct again!
4)I cannot delete the file from Dos shell or from W2K explorer
which is correct.
5)However, I can overwrite the file over with:
E:\copy d:\log.txt log.txt
1 file(s) copied.
Which is WRONG as is me being able to copy another file over it
with W2K explorer too.
Is there a way around this? How can I stop file being COPIED OVER while
it is being open? Is this window's feature? Is readlines() operation
atomic enough for me not to worry about these issues?
My python script modifies set of files from a directory one by one.
I try to lock them all exclusively for the script
until all are modified. If one of the files gets overwritten
by another version (by another process) the script may fail.
-pekka-





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


File locking is impossible in Windows?

2004-12-21 Thread Pekka Niiranen
Hi,
I have used the following example from win32 extensions:
-SCRIPT STARTS
import win32file
import win32con
import win32security
import pywintypes
class Flock:
def __init__(self,file):
self.file=file
secur_att = win32security.SECURITY_ATTRIBUTES()
secur_att.Initialize()
self.highbits=-0x7fff
self.hfile=win32file.CreateFile( self.file,\
win32con.GENERIC_READ|win32con.GENERIC_WRITE,\
win32con.FILE_SHARE_READ|win32con.FILE_SHARE_WRITE,\
secur_att, win32con.OPEN_ALWAYS,\
win32con.FILE_ATTRIBUTE_NORMAL , 0 )
def lock(self):
lock_flags=win32con.LOCKFILE_EXCLUSIVE_LOCK|\
win32con.LOCKFILE_FAIL_IMMEDIATELY
self.ov=pywintypes.OVERLAPPED()
win32file.LockFileEx(self.hfile,lock_flags,0,\
self.highbits,self.ov)
def unlock(self):
win32file.UnlockFileEx(self.hfile,0,\
self.highbits,self.ov)
self.hfile.Close()
if __name__ == '__main__':
from time import time, strftime, localtime
import sys

l=Flock(e:log.txt)
print 'calling lock'
l.lock()
print Now locked.  Hit enter to release lock.
dummy = sys.stdin.readline()
l.unlock()
print 'now unlocked'
-SCRIPT ENDS
If I start one python process from dos window I get message:
E:\python lockker.py
calling lock
Now locked.  Hit enter to release lock.
All well, now if
1)  I start another Dos -shell and run the same command I get:
E:\python lockker.py
calling lock
Traceback (most recent call last):
  File lockker.py, line 35, in ?
l.lock()
  File lockker.py, line 23, in lock
   win32file.LockFileEx(self.hfile,lock_flags,0,\
   self.highbits,self.ov)
pywintypes.error: (33, 'LockFileEx',\
'The process cannot access the file because\
 another process has locked a portion of  the file.')
Which is correct.
2)  I try to read the contents of the file from Dos -shell, I get:
E:\type log.txt
The process cannot access the file because another\
process has locked a portion of the file.

This is correct.
3)  When I open the file into notepad.exe I can edit the screen
but not write changes to disk. Correct again!
4)  I cannot delete the file from Dos shell or from W2K explorer
which is correct.
5)  However, I can overwrite the file over with:
E:\copy d:\log.txt log.txt
1 file(s) copied.
Which is WRONG as is me being able to copy another file over it
with W2K explorer too.
Is there a way around this? How can I stop file being COPIED OVER while
it is being open? Is this window's feature? Is readlines() operation
atomic enough for me not to worry about these issues?
My python script modifies set of files from a directory one by one.
I try to lock them all exclusively for the script
until all are modified. If one of the files gets overwritten
by another version (by another process) the script may fail.
-pekka-



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


Bug in py32win manual for file_locking for Python 2.4

2004-12-04 Thread Pekka Niiranen
Hi,
I tried to lock file in w2k using example
directly from pyWin32 manual:
#--
 import pywintypes
 ov=pywintypes.OVERLAPPED() #used to indicate starting region to lock
 highbits=0x
 file=c:wilma.txt
 import win32file
 import win32security
 import win32api
 secur_att = win32security.SECURITY_ATTRIBUTES()
 secur_att.Initialize()
 hfile=win32file.CreateFile( file, \
... win32con.GENERIC_READ|win32con.GENERIC_WRITE, \
... win32con.FILE_SHARE_READ|win32con.FILE_SHARE_WRITE, \
... secur_att, \
... win32con.OPEN_ALWAYS, \
... win32con.FILE_ATTRIBUTE_NORMAL , 0 )
 
win32file.LockFileEx(hfile,win32con.LOCKFILE_EXCLUSIVE_LOCK,0,highbits,ov)
Traceback (most recent call last):
  File interactive input, line 1, in ?
OverflowError: long int too large to convert to int
#-

However, using
highbits=0x7fff # equals hex(sys.maxint)
gives no errors, but does locking work if
highbits are not exactly 0x?
Does anybody have example of locking the whole directory
in one go without looping thru its files?
-pekka-
--
http://mail.python.org/mailman/listinfo/python-list


Question of Optionparse

2004-11-29 Thread Pekka Niiranen
Hi,
How can I STOP Optionparse to process boolean
value as parameter. See this:
 parser = optparse.OptionParser()
 parser.add_option(-x,dest='xxx', action=store_true,help=xxx)
 parser.add_option(-r,dest='root',help=directory,type=string)
 args = [-r, d:, -x]
 parser.parse_args(args)
(Values at 0x13bbbc0: {'xxx': True, 'root': 'd:'}, [])
Last line is correct: boolean 'xxx' gets set 'True'
and parameter 'root' to 'd:'
However when value is NOT given for '-r' but '-x' exists:
 args = [-r, -x]
 parser.parse_args(args)
(Values at 0x13ccf80: {'xxx': None, 'root': '-x'}, [])
This is BS: I expected 'root' to be None and 'xxx' to be 'True'.
How can I make it so?
Another question: Is there a way to store options
directly into user defined dictionary without assignment
like this:
my_environment_values = {}
(options, args) = parser.parse_args()
environment_values[xxx] = options.xxx
-pekka-
--
http://mail.python.org/mailman/listinfo/python-list