[Pymoul-svn] SF.net SVN: pymoul: [86] pymoul/trunk
Status: Alpha
Brought to you by:
tiran
|
From: <ti...@us...> - 2007-01-26 18:46:01
|
Revision: 86
http://pymoul.svn.sourceforge.net/pymoul/?rev=86&view=rev
Author: tiran
Date: 2007-01-26 10:30:56 -0800 (Fri, 26 Jan 2007)
Log Message:
-----------
More cleanups: removed unused processinfo module
Removed dependency on pywin32 again. Apparently windows locks the file
Modified Paths:
--------------
pymoul/trunk/setup_win32.py
pymoul/trunk/src/moul/osdependent/singleapp.py
pymoul/trunk/src/moul/osdependent/tests/test_singleapp.py
Removed Paths:
-------------
pymoul/trunk/src/moul/osdependent/processinfo.py
Modified: pymoul/trunk/setup_win32.py
===================================================================
--- pymoul/trunk/setup_win32.py 2007-01-26 17:37:52 UTC (rev 85)
+++ pymoul/trunk/setup_win32.py 2007-01-26 18:30:56 UTC (rev 86)
@@ -71,9 +71,7 @@
pexe['includes'] = ['sip', 'PyQt4', 'encodings', 'encodings.*',
'moul.osdependent.win32', 'moul.osdependent.win32.*']
# SSL currently not in use but imported by socket
- pexe['excludes'] = ['_ssl']
- # added by platform but not yet required
- #pexe['excludes'].extend(('win32pipe', 'win32api', 'win32con', 'win32evtlog'))
+ pexe['excludes'] = ['_ssl', 'win32pipe', 'win32evtlog', 'win32file', 'win32api']
# added by logging.handlers.SMTPHandler but not yet required
pexe['excludes'].append('smtplib')
# UPX
Deleted: pymoul/trunk/src/moul/osdependent/processinfo.py
===================================================================
--- pymoul/trunk/src/moul/osdependent/processinfo.py 2007-01-26 17:37:52 UTC (rev 85)
+++ pymoul/trunk/src/moul/osdependent/processinfo.py 2007-01-26 18:30:56 UTC (rev 86)
@@ -1,219 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: iso-8859-1 -*-
-"""Process info
-
-Based on http://gelb.bcom.at/trac/misc/browser/processinfo
-
-Modified and optimized by Christian Heimes
-"""
-
-import sys
-import os
-
-__all__ = ['PLATFORM', 'UnsupportedOsError', 'getCurrentPids',
- 'getCurrentPidNames', 'getCurrentPidDetails']
-
-class UnsupportedOsError(NotImplementedError):
- pass
-
-PLATFORM = None
-
-_plat = sys.platform.startswith
-if _plat('win'):
- PLATFORM = 'win'
- win32process = None
- ctypes = None
- import csv
- try:
- import win32process
- except ImportError:
- try:
- import ctypes
- except ImportError:
- pass
-elif _plat('linux2') or _plat('cygwin'):
- PLATFORM = 'linux' # Linux or Cygwin
-elif _plat('darwin'):
- # XXX: unsupported
- PLATFORM = 'mac' # Mac OS X
-elif _plat('freebsd') or _plat('netbsd') or _plat('openbsd'):
- # XXX: unsupported
- PLATFORM = 'bsd' # *BSD
-else:
- PLATFORM = 'unknown'
- raise UnsupportedOsError(sys.platform)
-
-# ****************************************************************************
-# Linux / cygwin implementation
-
-def _getCurrentPids_linux():
- """
- Returns current process-id's.
-
- :return: list with process-id's.
- """
- pids = []
- for fname in os.listdir("/proc"):
- if os.path.isdir(os.path.join("/proc", fname)):
- try:
- pids.append(int(fname))
- except ValueError:
- continue
- return pids
-
-def _getCurrentPidDetails_linux():
- """Returns mapping pid -> detailed informations
- """
- mapping = {}
- for pid in getCurrentPids():
- try:
- try:
- # read entiry file to avoid race condition bugs
- fd = open('/proc/%i/status' % pid, 'rb')
- status = fd.read().split('\n')
- finally:
- if fd:
- fd.close()
- except IoError:
- continue
- details = {}
- for line in status:
- try:
- key, value = line.split(':\t')
- except ValueError:
- continue
- details[key.lower()] = value.strip()
- mapping[pid] = details
-
- return mapping
-
-def _getCurrentPidNames_linux():
- """Returns mapping pid -> name
- """
- mapping = {}
- for pid, details in getCurrentPidDetails().items():
- mapping[pid] = details.get('name', None)
- return mapping
-
-
-# ****************************************************************************
-# Windows / win32 implementaton
-
-def _getCurrentPids_win():
- """
- Returns current process-id's.
-
- :return: List with process-id's.
- """
- if win32process is not None:
- return list(win32process.EnumProcesses())
- elif ctypes is not None:
- # ctypes is installed --> try psapi.dll
- psapi = ct.windll.psapi
- arr = ct.c_long * 1024
- process_ids = arr()
- cb = ct.sizeof(process_ids)
- bytes_returned = ct.c_ulong()
- psapi.EnumProcesses(ct.byref(process_ids), cb, ct.byref(bytes_returned))
- return sorted(list(set(process_ids)))
- else:
- csvlines = []
- current_pids = []
- for line in os.popen("tasklist.exe /fo csv /nh"):
- line = line.strip()
- if line:
- csvlines.append(line)
- for line in csv.reader(csvlines):
- current_pids.append(int(line[1]))
- if not csvlines:
- raise NotImplementedError("tasklist.exe not found (>WinXP)")
- return current_pids
-
-def _getCurrentPidNames_win():
- """Returns mapping pid -> name
- """
- mapping = {}
- for pid, details in getCurrentPidDetails().items():
- mapping[pid] = details.get('name', None)
- return mapping
-
-def _getCurrentPidDetails_win():
- """
- Returns processinfos. (pid, name and size_kb)
- """
- result = {}
-
- # tasklist.exe runs on Windows XP and higher. (To parse the ouput of
- # tasklist.exe is faster than WMI.)
- csvlines = []
- for line in os.popen("tasklist.exe /fo csv /nh"):
- line = line.strip()
- if line:
- csvlines.append(line)
- for line in csv.reader(csvlines):
- pid = int(line[1])
- details = {
- "name": line[0].decode("cp850"), # to unicode
- "pid": pid,
- }
- value = "".join(
- char for char in line[4]
- if char.isdigit()
- )
- details["size_kb"] = int(value)
- retdict[pid] = details
- if not csvlines:
- try:
- from win32com.client import GetObject
- # pywin32 is installed --> use WMI
- wmi = GetObject('winmgmts:')
- processes = wmi.InstancesOf('Win32_Process')
- for process in processes:
- pid = int(process.Properties_("ProcessId").value)
- details = {
- "name": process.Properties_("Name").value,
- "pid": pid,
- "size_kb": int(process.Properties_("WorkingSetSize").value) / 1000
- }
- retdict[pid] = details
- except ImportError:
- raise NotImplementedError("No tasklist.exe and no WMI.")
- return retdict
-
-# ****************************************************************************
-# general
-
-def unsupported():
- """Platform not supported
- """
- raise UnsupportedOsError(PLATFORM)
-unsupported.__unsupported__ = True
-
-def _initialize():
- mod = sys.modules[__name__]
- for name in ('getCurrentPids','getCurrentPidDetails', 'getCurrentPidNames'):
- func = getattr(mod, "_%s_%s" % (name, PLATFORM), None)
- if func is None:
- func = unsupported
- else:
- func.__name__ = name
- setattr(mod, name, func)
-_initialize()
-
-def main():
- """Testing"""
-
- from pprint import pformat
- # Current PIDs
- current_pids = getCurrentPids()
- print "Current PIDs: %s" % pformat(current_pids)
- print
- print "Current PID Count: %s" % len(current_pids)
- print
-
- print "Current PIDs with names: %s" % pformat(getCurrentPidNames())
- print
-
-if __name__ == "__main__":
- main()
-
Modified: pymoul/trunk/src/moul/osdependent/singleapp.py
===================================================================
--- pymoul/trunk/src/moul/osdependent/singleapp.py 2007-01-26 17:37:52 UTC (rev 85)
+++ pymoul/trunk/src/moul/osdependent/singleapp.py 2007-01-26 18:30:56 UTC (rev 86)
@@ -25,11 +25,12 @@
Boiler plate
>>> import sys
>>> from shutil import rmtree
->>> from subprocess import call
+>>> from subprocess import Popen
+>>> from StringIO import StringIO
>>> tmpdir = tempfile.mkdtemp()
>>> testfile = os.path.join(tmpdir, 'test.lck')
>>> if os.name == 'nt':
-... rm = "del"
+... rm = "cmd /c del"
... else:
... rm = "rm"
@@ -39,20 +40,29 @@
>>> fn1 = fd1.fileno()
>>> lock(fd1, flags)
>>> fd1.write('testdata')
+>>> os.path.isfile(testfile)
+True
Try to delete the file from another process
->>> try:
-... retcode = call("%s %s" % (rm, testfile))
-... except:
-... typ, value, tb = sys.exc_info()
-... del tb
-... else:
-... print "Should have raised an error!"
+>>> stdout = tempfile.TemporaryFile(mode="w+")
+>>> stderr = tempfile.TemporaryFile(mode="w+")
+>>> popen = Popen("%s %s" % (rm, testfile), stdout=stdout, stderr=stderr)
+>>> popen.wait()
+0
-On Windows the error is WindowsError based on OSError
->>> issubclass(typ, OSError) or typ
+>>> stdout.seek(0)
+>>> out = stdout.read()
+>>> if os.name == 'nt':
+... out.endswith('test.lck\\n') or out
True
+>>> stderr.seek(0)
+>>> stderr.read() != ''
+True
+
+>>> os.path.isfile(testfile)
+True
+
Clean up
>>> unlock(fd1)
>>> fd1.close()
@@ -86,17 +96,19 @@
USER = getpass.getuser()
PID = os.getpid()
+# PYWIN32: Apparently windows locks a file automatically
if os.name == 'nt':
- import win32con
- import win32file
- import pywintypes
- LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
- LOCK_SH = 0 # the default
- LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY
- lowbits, highbits = 0, -65536
+# import win32con
+# import win32file
+# import pywintypes
+# LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
+# LOCK_SH = 0 # the default
+# LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY
+# lowbits, highbits = 0, -65536
+ LOCK_SH, LOCK_NB = 0, 1
elif os.name == 'posix':
import fcntl
- LOCK_EX = fcntl.LOCK_EX
+ #LOCK_EX = fcntl.LOCK_EX
LOCK_SH = fcntl.LOCK_SH
LOCK_NB = fcntl.LOCK_NB
else:
@@ -104,11 +116,13 @@
if os.name == 'nt':
def lock(file, flags):
- hfile = win32file._get_osfhandle(file.fileno())
- return win32file.LockFileEx(hfile, flags, lowbits, highbits, pywintypes.OVERLAPPED())
+ #hfile = win32file._get_osfhandle(file.fileno())
+ #return win32file.LockFileEx(hfile, flags, lowbits, highbits, pywintypes.OVERLAPPED())
+ pass
def unlock(file):
- hfile = win32file._get_osfhandle(file.fileno())
- return win32file.UnlockFileEx(hfile, lowbits, highbits, pywintypes.OVERLAPPED())
+ #hfile = win32file._get_osfhandle(file.fileno())
+ #return win32file.UnlockFileEx(hfile, lowbits, highbits, pywintypes.OVERLAPPED())
+ pass
elif os.name =='posix':
def lock(file, flags):
return fcntl.flock(file.fileno(), flags)
@@ -141,6 +155,12 @@
May raise an OSError
"""
+ if os.path.isfile(self.lckfile):
+ try:
+ os.unlink(self.lckfile)
+ except OSError, IOError:
+ self._fd = None
+ raise SingleAppError("Another instance is already running")
try:
self._fd = open(self.lckfile, 'w')
self._fd.write(str(self.pid))
Modified: pymoul/trunk/src/moul/osdependent/tests/test_singleapp.py
===================================================================
--- pymoul/trunk/src/moul/osdependent/tests/test_singleapp.py 2007-01-26 17:37:52 UTC (rev 85)
+++ pymoul/trunk/src/moul/osdependent/tests/test_singleapp.py 2007-01-26 18:30:56 UTC (rev 86)
@@ -27,7 +27,7 @@
from moul.osdependent.singleapp import SimpleSingleApp
from moul.osdependent.singleapp import lock
from moul.osdependent.singleapp import unlock
-from moul.osdependent.singleapp import LOCK_EX, LOCK_SH, LOCK_NB
+from moul.osdependent.singleapp import LOCK_SH, LOCK_NB
def test_suite():
return unittest.TestSuite((
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|