home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_642 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  12.5 KB  |  402 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import os
  5. import sys
  6. import signal
  7. from multiprocessing import util, process
  8. __all__ = [
  9.     'Popen',
  10.     'assert_spawning',
  11.     'exit',
  12.     'duplicate',
  13.     'close',
  14.     'ForkingPickler']
  15.  
  16. def assert_spawning(self):
  17.     if not Popen.thread_is_spawning():
  18.         raise RuntimeError('%s objects should only be shared between processes through inheritance' % type(self).__name__)
  19.     Popen.thread_is_spawning()
  20.  
  21. from pickle import Pickler
  22.  
  23. class ForkingPickler(Pickler):
  24.     dispatch = Pickler.dispatch.copy()
  25.     
  26.     def register(cls, type, reduce):
  27.         
  28.         def dispatcher(self, obj):
  29.             rv = reduce(obj)
  30.             self.save_reduce(obj = obj, *rv)
  31.  
  32.         cls.dispatch[type] = dispatcher
  33.  
  34.     register = classmethod(register)
  35.  
  36.  
  37. def _reduce_method(m):
  38.     if m.im_self is None:
  39.         return (getattr, (m.im_class, m.im_func.func_name))
  40.     return (getattr, (m.im_self, m.im_func.func_name))
  41.  
  42. ForkingPickler.register(type(ForkingPickler.save), _reduce_method)
  43.  
  44. def _reduce_method_descriptor(m):
  45.     return (getattr, (m.__objclass__, m.__name__))
  46.  
  47. ForkingPickler.register(type(list.append), _reduce_method_descriptor)
  48. ForkingPickler.register(type(int.__add__), _reduce_method_descriptor)
  49.  
  50. try:
  51.     from functools import partial
  52. except ImportError:
  53.     pass
  54.  
  55.  
  56. def _reduce_partial(p):
  57.     if not p.keywords:
  58.         pass
  59.     return (_rebuild_partial, (p.func, p.args, { }))
  60.  
  61.  
  62. def _rebuild_partial(func, args, keywords):
  63.     return partial(func, *args, **keywords)
  64.  
  65. ForkingPickler.register(partial, _reduce_partial)
  66. if sys.platform != 'win32':
  67.     import time
  68.     exit = os._exit
  69.     duplicate = os.dup
  70.     close = os.close
  71.     
  72.     class Popen(object):
  73.         
  74.         def __init__(self, process_obj):
  75.             sys.stdout.flush()
  76.             sys.stderr.flush()
  77.             self.returncode = None
  78.             self.pid = os.fork()
  79.             if self.pid == 0:
  80.                 if 'random' in sys.modules:
  81.                     import random
  82.                     random.seed()
  83.                 
  84.                 code = process_obj._bootstrap()
  85.                 sys.stdout.flush()
  86.                 sys.stderr.flush()
  87.                 os._exit(code)
  88.             
  89.  
  90.         
  91.         def poll(self, flag = os.WNOHANG):
  92.             if self.returncode is None:
  93.                 (pid, sts) = os.waitpid(self.pid, flag)
  94.                 if pid == self.pid:
  95.                     if os.WIFSIGNALED(sts):
  96.                         self.returncode = -os.WTERMSIG(sts)
  97.                     else:
  98.                         self.returncode = os.WEXITSTATUS(sts)
  99.                 
  100.             
  101.             return self.returncode
  102.  
  103.         
  104.         def wait(self, timeout = None):
  105.             if timeout is None:
  106.                 return self.poll(0)
  107.             deadline = time.time() + timeout
  108.             delay = 0.0005
  109.             while None:
  110.                 res = self.poll()
  111.                 if res is not None:
  112.                     break
  113.                 
  114.                 remaining = deadline - time.time()
  115.                 if remaining <= 0:
  116.                     break
  117.                 
  118.                 delay = min(delay * 2, remaining, 0.05)
  119.                 continue
  120.                 return res
  121.  
  122.         
  123.         def terminate(self):
  124.             if self.returncode is None:
  125.                 
  126.                 try:
  127.                     os.kill(self.pid, signal.SIGTERM)
  128.                 except OSError:
  129.                     e = None
  130.                     if self.wait(timeout = 0.1) is None:
  131.                         raise 
  132.                     self.wait(timeout = 0.1) is None
  133.                 except:
  134.                     None<EXCEPTION MATCH>OSError
  135.                 
  136.  
  137.             None<EXCEPTION MATCH>OSError
  138.  
  139.         
  140.         def thread_is_spawning():
  141.             return False
  142.  
  143.         thread_is_spawning = staticmethod(thread_is_spawning)
  144.  
  145. else:
  146.     import thread
  147.     import msvcrt
  148.     import _subprocess
  149.     import time
  150.     from _multiprocessing import win32, Connection, PipeConnection
  151.     from util import Finalize
  152.     from pickle import load, HIGHEST_PROTOCOL
  153.     
  154.     def dump(obj, file, protocol = None):
  155.         ForkingPickler(file, protocol).dump(obj)
  156.  
  157.     TERMINATE = 65536
  158.     if sys.platform == 'win32':
  159.         pass
  160.     WINEXE = getattr(sys, 'frozen', False)
  161.     exit = win32.ExitProcess
  162.     close = win32.CloseHandle
  163.     if sys.executable.lower().endswith('pythonservice.exe'):
  164.         _python_exe = os.path.join(sys.exec_prefix, 'python.exe')
  165.     else:
  166.         _python_exe = sys.executable
  167.     
  168.     def set_executable(exe):
  169.         global _python_exe
  170.         _python_exe = exe
  171.  
  172.     
  173.     def duplicate(handle, target_process = None, inheritable = False):
  174.         if target_process is None:
  175.             target_process = _subprocess.GetCurrentProcess()
  176.         
  177.         return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(), handle, target_process, 0, inheritable, _subprocess.DUPLICATE_SAME_ACCESS).Detach()
  178.  
  179.     
  180.     class Popen(object):
  181.         _tls = thread._local()
  182.         
  183.         def __init__(self, process_obj):
  184.             (rfd, wfd) = os.pipe()
  185.             rhandle = duplicate(msvcrt.get_osfhandle(rfd), inheritable = True)
  186.             os.close(rfd)
  187.             cmd = get_command_line() + [
  188.                 rhandle]
  189.             cmd = ' '.join((lambda .0: for x in .0:
  190. '"%s"' % x)(cmd))
  191.             (hp, ht, pid, tid) = _subprocess.CreateProcess(_python_exe, cmd, None, None, 1, 0, None, None, None)
  192.             ht.Close()
  193.             close(rhandle)
  194.             self.pid = pid
  195.             self.returncode = None
  196.             self._handle = hp
  197.             prep_data = get_preparation_data(process_obj._name)
  198.             to_child = os.fdopen(wfd, 'wb')
  199.             Popen._tls.process_handle = int(hp)
  200.             
  201.             try:
  202.                 dump(prep_data, to_child, HIGHEST_PROTOCOL)
  203.                 dump(process_obj, to_child, HIGHEST_PROTOCOL)
  204.             finally:
  205.                 del Popen._tls.process_handle
  206.                 to_child.close()
  207.  
  208.  
  209.         
  210.         def thread_is_spawning():
  211.             return getattr(Popen._tls, 'process_handle', None) is not None
  212.  
  213.         thread_is_spawning = staticmethod(thread_is_spawning)
  214.         
  215.         def duplicate_for_child(handle):
  216.             return duplicate(handle, Popen._tls.process_handle)
  217.  
  218.         duplicate_for_child = staticmethod(duplicate_for_child)
  219.         
  220.         def wait(self, timeout = None):
  221.             if self.returncode is None:
  222.                 if timeout is None:
  223.                     msecs = _subprocess.INFINITE
  224.                 else:
  225.                     msecs = max(0, int(timeout * 1000 + 0.5))
  226.                 res = _subprocess.WaitForSingleObject(int(self._handle), msecs)
  227.                 if res == _subprocess.WAIT_OBJECT_0:
  228.                     code = _subprocess.GetExitCodeProcess(self._handle)
  229.                     if code == TERMINATE:
  230.                         code = -(signal.SIGTERM)
  231.                     
  232.                     self.returncode = code
  233.                 
  234.             
  235.             return self.returncode
  236.  
  237.         
  238.         def poll(self):
  239.             return self.wait(timeout = 0)
  240.  
  241.         
  242.         def terminate(self):
  243.             if self.returncode is None:
  244.                 
  245.                 try:
  246.                     _subprocess.TerminateProcess(int(self._handle), TERMINATE)
  247.                 except WindowsError:
  248.                     if self.wait(timeout = 0.1) is None:
  249.                         raise 
  250.                     self.wait(timeout = 0.1) is None
  251.                 except:
  252.                     None<EXCEPTION MATCH>WindowsError
  253.                 
  254.  
  255.             None<EXCEPTION MATCH>WindowsError
  256.  
  257.  
  258.     
  259.     def is_forking(argv):
  260.         if len(argv) >= 2 and argv[1] == '--multiprocessing-fork':
  261.             return True
  262.         return False
  263.  
  264.     
  265.     def freeze_support():
  266.         if is_forking(sys.argv):
  267.             main()
  268.             sys.exit()
  269.         
  270.  
  271.     
  272.     def get_command_line():
  273.         if process.current_process()._identity == () and is_forking(sys.argv):
  274.             raise RuntimeError('\n            Attempt to start a new process before the current process\n            has finished its bootstrapping phase.\n\n            This probably means that you are on Windows and you have\n            forgotten to use the proper idiom in the main module:\n\n                if __name__ == \'__main__\':\n                    freeze_support()\n                    ...\n\n            The "freeze_support()" line can be omitted if the program\n            is not going to be frozen to produce a Windows executable.')
  275.         is_forking(sys.argv)
  276.         if getattr(sys, 'frozen', False):
  277.             return [
  278.                 sys.executable,
  279.                 '--multiprocessing-fork']
  280.         prog = 'from multiprocessing.forking import main; main()'
  281.         return [
  282.             _python_exe,
  283.             '-c',
  284.             prog,
  285.             '--multiprocessing-fork']
  286.  
  287.     
  288.     def main():
  289.         handle = int(sys.argv[-1])
  290.         fd = msvcrt.open_osfhandle(handle, os.O_RDONLY)
  291.         from_parent = os.fdopen(fd, 'rb')
  292.         process.current_process()._inheriting = True
  293.         preparation_data = load(from_parent)
  294.         prepare(preparation_data)
  295.         self = load(from_parent)
  296.         process.current_process()._inheriting = False
  297.         from_parent.close()
  298.         exitcode = self._bootstrap()
  299.         exit(exitcode)
  300.  
  301.     
  302.     def get_preparation_data(name):
  303.         _logger = _logger
  304.         _log_to_stderr = _log_to_stderr
  305.         import util
  306.         d = dict(name = name, sys_path = sys.path, sys_argv = sys.argv, log_to_stderr = _log_to_stderr, orig_dir = process.ORIGINAL_DIR, authkey = process.current_process().authkey)
  307.         if _logger is not None:
  308.             d['log_level'] = _logger.getEffectiveLevel()
  309.         
  310.         if not WINEXE:
  311.             main_path = getattr(sys.modules['__main__'], '__file__', None)
  312.             if not main_path and sys.argv[0] not in ('', '-c'):
  313.                 main_path = sys.argv[0]
  314.             
  315.             if main_path is not None:
  316.                 if not os.path.isabs(main_path) and process.ORIGINAL_DIR is not None:
  317.                     main_path = os.path.join(process.ORIGINAL_DIR, main_path)
  318.                 
  319.                 d['main_path'] = os.path.normpath(main_path)
  320.             
  321.         
  322.         return d
  323.  
  324.     
  325.     def reduce_connection(conn):
  326.         if not Popen.thread_is_spawning():
  327.             raise RuntimeError('By default %s objects can only be shared between processes\nusing inheritance' % type(conn).__name__)
  328.         Popen.thread_is_spawning()
  329.         return (type(conn), (Popen.duplicate_for_child(conn.fileno()), conn.readable, conn.writable))
  330.  
  331.     ForkingPickler.register(Connection, reduce_connection)
  332.     ForkingPickler.register(PipeConnection, reduce_connection)
  333. old_main_modules = []
  334.  
  335. def prepare(data):
  336.     old_main_modules.append(sys.modules['__main__'])
  337.     if 'name' in data:
  338.         process.current_process().name = data['name']
  339.     
  340.     if 'authkey' in data:
  341.         process.current_process()._authkey = data['authkey']
  342.     
  343.     if 'log_to_stderr' in data and data['log_to_stderr']:
  344.         util.log_to_stderr()
  345.     
  346.     if 'log_level' in data:
  347.         util.get_logger().setLevel(data['log_level'])
  348.     
  349.     if 'sys_path' in data:
  350.         sys.path = data['sys_path']
  351.     
  352.     if 'sys_argv' in data:
  353.         sys.argv = data['sys_argv']
  354.     
  355.     if 'dir' in data:
  356.         os.chdir(data['dir'])
  357.     
  358.     if 'orig_dir' in data:
  359.         process.ORIGINAL_DIR = data['orig_dir']
  360.     
  361.     if 'main_path' in data:
  362.         main_path = data['main_path']
  363.         main_name = os.path.splitext(os.path.basename(main_path))[0]
  364.         if main_name == '__init__':
  365.             main_name = os.path.basename(os.path.dirname(main_path))
  366.         
  367.         if main_name != 'ipython':
  368.             import imp
  369.             if main_path is None:
  370.                 dirs = None
  371.             elif os.path.basename(main_path).startswith('__init__.py'):
  372.                 dirs = [
  373.                     os.path.dirname(os.path.dirname(main_path))]
  374.             else:
  375.                 dirs = [
  376.                     os.path.dirname(main_path)]
  377.             (file, path_name, etc) = imp.find_module(main_name, dirs)
  378.             
  379.             try:
  380.                 main_module = imp.load_module('__parents_main__', file, path_name, etc)
  381.             finally:
  382.                 if file:
  383.                     file.close()
  384.                 
  385.  
  386.             sys.modules['__main__'] = main_module
  387.             main_module.__name__ = '__main__'
  388.             for obj in main_module.__dict__.values():
  389.                 
  390.                 try:
  391.                     if obj.__module__ == '__parents_main__':
  392.                         obj.__module__ = '__main__'
  393.                 continue
  394.                 except Exception:
  395.                     continue
  396.                 
  397.  
  398.             
  399.         
  400.     
  401.  
  402.