Python sys.frozen() Examples

The following are 30 code examples of sys.frozen(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sys , or try the search function .
Example #1
Source File: applications.py    From zim-desktop-wiki with GNU General Public License v2.0 6 votes vote down vote up
def testPythonCmd(self):
		app = Application('foo.py')
		cwd, argv = app._checkargs(None, ())
		self.assertEqual(argv[0], sys.executable)
		self.assertEqual(argv[1], 'foo.py')

		sys.frozen = True
		try:
			cwd, argv = app._checkargs(None, ())
			self.assertEqual(argv, ('foo.py',))
		except:
			del sys.frozen
			raise
		else:
			del sys.frozen

	# TODO fully test _decode_value
	# test e.g. values with '"' or '\t' in a string
	# see that json.loads does what it is supposed to do 
Example #2
Source File: xmlstuff.py    From peach with Mozilla Public License 2.0 6 votes vote down vote up
def __init__(self, group, testFiles=None):
        """
        @type	group: Group
        @param	group: Group this Generator belongs to
        @type	testFiles: string
        @param	testFiles: Location of test files
        """
        Generator.__init__(self)

        p = None
        if not (hasattr(sys, "frozen") and sys.frozen == "console_exe"):
            p = Peach.Generators.static.__file__[:-10]
        else:
            p = os.path.dirname(os.path.abspath(sys.executable))

        testFiles = os.path.join(p, "xmltests")

        self._generatorList = GeneratorList(group,
                                            [XmlParserTestsInvalid(None, testFiles),
                                             XmlParserTestsNotWellFormed(None, testFiles),
                                             XmlParserTestsValid(None, testFiles)]) 
Example #3
Source File: site.py    From build-calibre with GNU General Public License v3.0 6 votes vote down vote up
def main():
    global __file__

    # Needed on OS X <= 10.8, which passes -psn_... as a command line arg when
    # starting via launch services
    for arg in tuple(sys.argv[1:]):
        if arg.startswith('-psn_'):
            sys.argv.remove(arg)

    base = sys.resourcepath
    sys.frozen = 'macosx_app'
    sys.new_app_bundle = True
    abs__file__()

    add_calibre_vars(base)
    addsitedir(sys.site_packages)

    if sys.calibre_is_gui_app and not (
            sys.stdout.isatty() or sys.stderr.isatty() or sys.stdin.isatty()):
        nuke_stdout()

    return run_entry_point() 
Example #4
Source File: site.py    From build-calibre with GNU General Public License v3.0 6 votes vote down vote up
def main():
    sys.frozen = 'windows_exe'
    sys.setdefaultencoding('utf-8')
    aliasmbcs()

    sys.meta_path.insert(0, PydImporter())
    sys.path_importer_cache.clear()

    import linecache
    def fake_getline(filename, lineno, module_globals=None):
        return ''
    linecache.orig_getline = linecache.getline
    linecache.getline = fake_getline

    abs__file__()

    add_calibre_vars()

    # Needed for pywintypes to be able to load its DLL
    sys.path.append(os.path.join(sys.app_dir, 'app', 'DLLs'))

    return run_entry_point() 
Example #5
Source File: update.py    From EDMarketConnector with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, master):
            try:
                sys.frozen	# don't want to try updating python.exe
                self.updater = ctypes.cdll.WinSparkle
                self.updater.win_sparkle_set_appcast_url(update_feed)	# py2exe won't let us embed this in resources

                # set up shutdown callback
                global root
                root = master
                self.callback_t = ctypes.CFUNCTYPE(None)	# keep reference
                self.callback_fn = self.callback_t(shutdown_request)
                self.updater.win_sparkle_set_shutdown_request_callback(self.callback_fn)

                self.updater.win_sparkle_init()

            except:
                from traceback import print_exc
                print_exc()
                self.updater = None 
Example #6
Source File: util.py    From artisan with GNU General Public License v3.0 6 votes vote down vote up
def appFrozen():
    ib = False
    try:
        platf = str(platform.system())
        if platf == "Darwin":
            # the sys.frozen is set by py2app and pyinstaller and is unset otherwise
            if getattr( sys, 'frozen', False ):
                ib = True
        elif platf == "Windows":
            ib = (hasattr(sys, "frozen") or # new py2exe
                hasattr(sys, "importers") # old py2exe
                or imp.is_frozen("__main__")) # tools/freeze
        elif platf == "Linux":
            if getattr(sys, 'frozen', False):
                # The application is frozen
                ib = True
    except Exception:
        pass
    return ib 
Example #7
Source File: test_path.py    From Computable with MIT License 6 votes vote down vote up
def teardown_environment():
    """Restore things that were remembered by the setup_environment function
    """
    (oldenv, os.name, sys.platform, path.get_home_dir, IPython.__file__, old_wd) = oldstuff
    os.chdir(old_wd)
    reload(path)

    for key in env.keys():
        if key not in oldenv:
            del env[key]
    env.update(oldenv)
    if hasattr(sys, 'frozen'):
        del sys.frozen
    if os.name == 'nt':
        (wreg.OpenKey, wreg.QueryValueEx,) = platformstuff

# Build decorator that uses the setup_environment/setup_environment 
Example #8
Source File: NextID.py    From ConTroll_Remote_Access_Trojan with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        import win32api
        win32api.MessageBox(0, "NextID.__init__ started", "NextID.py")
        global d
        if sys.frozen:
            for entry in sys.path:
                if entry.find('?') > -1:
                    here = os.path.dirname(entry.split('?')[0])
                    break
            else:
                here = os.getcwd()
        else:
            here = os.path.dirname(__file__)
        self.fnm = os.path.join(here, 'id.cfg')
        try:
            d = eval(open(self.fnm, 'rU').read()+'\n')
        except:
            d = {
                'systemID': 0xaaaab,
                'highID': 0
            }
        win32api.MessageBox(0, "NextID.__init__ complete", "NextID.py") 
Example #9
Source File: test_utils.py    From geofront-cli with GNU General Public License v3.0 5 votes vote down vote up
def test_unfrozen_dev_toplevel(self):
        """Not frozen, return path to bin dir."""
        path = get_program_path("foo", fallback_dirs=['/path/to/bin'])
        self.assertEquals(path, os.path.join("/path/to/bin", "foo")) 
Example #10
Source File: wrapper.py    From python-ovrsdk with Do What The F*ck You Want To Public License 5 votes vote down vote up
def getdirs(self,libname):
        '''Implements the dylib search as specified in Apple documentation:

        http://developer.apple.com/documentation/DeveloperTools/Conceptual/
            DynamicLibraries/Articles/DynamicLibraryUsageGuidelines.html

        Before commencing the standard search, the method first checks
        the bundle's ``Frameworks`` directory if the application is running
        within a bundle (OS X .app).
        '''

        dyld_fallback_library_path = _environ_path("DYLD_FALLBACK_LIBRARY_PATH")
        if not dyld_fallback_library_path:
            dyld_fallback_library_path = [os.path.expanduser('~/lib'),
                                          '/usr/local/lib', '/usr/lib']

        dirs = []

        if '/' in libname:
            dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))
        else:
            dirs.extend(_environ_path("LD_LIBRARY_PATH"))
            dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))

        dirs.extend(self.other_dirs)
        dirs.append(".")
        dirs.append(os.path.dirname(__file__))

        if hasattr(sys, 'frozen') and sys.frozen == 'macosx_app':
            dirs.append(os.path.join(
                os.environ['RESOURCEPATH'],
                '..',
                'Frameworks'))

        dirs.extend(dyld_fallback_library_path)

        return dirs

# Posix 
Example #11
Source File: local.py    From shadowsocks with Apache License 2.0 5 votes vote down vote up
def main():
    shell.check_python()

    # fix py2exe
    if hasattr(sys, "frozen") and sys.frozen in \
            ("windows_exe", "console_exe"):
        p = os.path.dirname(os.path.abspath(sys.executable))
        os.chdir(p)

    config = shell.get_config(True)

    daemon.daemon_exec(config)

    try:
        logging.info("starting local at %s:%d" %
                     (config['local_address'], config['local_port']))

        dns_resolver = asyncdns.DNSResolver()
        tcp_server = tcprelay.TCPRelay(config, dns_resolver, True)
        udp_server = udprelay.UDPRelay(config, dns_resolver, True)
        loop = eventloop.EventLoop()
        dns_resolver.add_to_loop(loop)
        tcp_server.add_to_loop(loop)
        udp_server.add_to_loop(loop)

        def handler(signum, _):
            logging.warn('received SIGQUIT, doing graceful shutting down..')
            tcp_server.close(next_tick=True)
            udp_server.close(next_tick=True)
        signal.signal(getattr(signal, 'SIGQUIT', signal.SIGTERM), handler)

        def int_handler(signum, _):
            sys.exit(1)
        signal.signal(signal.SIGINT, int_handler)

        daemon.set_user(config.get('user', None))
        loop.run()
    except Exception as e:
        shell.print_exception(e)
        sys.exit(1) 
Example #12
Source File: utils.py    From openxenmanager with GNU General Public License v2.0 5 votes vote down vote up
def we_are_frozen():
    if hasattr(sys, 'frozen') and sys.frozen in ('windows_exe', 'console_exe'):
        return hasattr(sys, 'frozen') 
Example #13
Source File: local.py    From shadowsocks-rm with Apache License 2.0 5 votes vote down vote up
def main():
    shell.check_python()

    # fix py2exe
    if hasattr(sys, "frozen") and sys.frozen in \
            ("windows_exe", "console_exe"):
        p = os.path.dirname(os.path.abspath(sys.executable))
        os.chdir(p)

    config = shell.get_config(True)

    daemon.daemon_exec(config)

    try:
        logging.info("starting local at %s:%d" %
                     (config['local_address'], config['local_port']))

        dns_resolver = asyncdns.DNSResolver()
        tcp_server = tcprelay.TCPRelay(config, dns_resolver, True)
        udp_server = udprelay.UDPRelay(config, dns_resolver, True)
        loop = eventloop.EventLoop()
        dns_resolver.add_to_loop(loop)
        tcp_server.add_to_loop(loop)
        udp_server.add_to_loop(loop)

        def handler(signum, _):
            logging.warn('received SIGQUIT, doing graceful shutting down..')
            tcp_server.close(next_tick=True)
            udp_server.close(next_tick=True)
        signal.signal(getattr(signal, 'SIGQUIT', signal.SIGTERM), handler)

        def int_handler(signum, _):
            sys.exit(1)
        signal.signal(signal.SIGINT, int_handler)

        daemon.set_user(config.get('user', None))
        loop.run()
    except Exception as e:
        shell.print_exception(e)
        sys.exit(1) 
Example #14
Source File: local.py    From ShadowSocks with Apache License 2.0 5 votes vote down vote up
def main():
    shell.check_python()

    # fix py2exe
    if hasattr(sys, "frozen") and sys.frozen in \
            ("windows_exe", "console_exe"):
        p = os.path.dirname(os.path.abspath(sys.executable))
        os.chdir(p)

    config = shell.get_config(True)

    daemon.daemon_exec(config)

    try:
        logging.info("starting local at %s:%d" %
                     (config['local_address'], config['local_port']))

        dns_resolver = asyncdns.DNSResolver()
        tcp_server = tcprelay.TCPRelay(config, dns_resolver, True)
        udp_server = udprelay.UDPRelay(config, dns_resolver, True)
        loop = eventloop.EventLoop()
        dns_resolver.add_to_loop(loop)
        tcp_server.add_to_loop(loop)
        udp_server.add_to_loop(loop)

        def handler(signum, _):
            logging.warn('received SIGQUIT, doing graceful shutting down..')
            tcp_server.close(next_tick=True)
            udp_server.close(next_tick=True)
        signal.signal(getattr(signal, 'SIGQUIT', signal.SIGTERM), handler)

        def int_handler(signum, _):
            sys.exit(1)
        signal.signal(signal.SIGINT, int_handler)

        daemon.set_user(config.get('user', None))
        loop.run()
    except Exception as e:
        shell.print_exception(e)
        sys.exit(1) 
Example #15
Source File: __boot__.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def _run():
    global __file__
    import os
    import site  # noqa: F401
    sys.frozen = 'macosx_app'
    base = os.environ['RESOURCEPATH']

    argv0 = os.path.basename(os.environ['ARGVZERO'])
    script = SCRIPT_MAP.get(argv0, DEFAULT_SCRIPT)  # noqa: F821

    path = os.path.join(base, script)
    sys.argv[0] = __file__ = path
    if sys.version_info[0] == 2:
        with open(path, 'rU') as fp:
            source = fp.read() + "\n"
    else:
        with open(path, 'rb') as fp:
            encoding = guess_encoding(fp)

        with open(path, 'r', encoding=encoding) as fp:
            source = fp.read() + '\n'

        BOM = b'\xef\xbb\xbf'.decode('utf-8')
        if source.startswith(BOM):
            source = source[1:]

    exec(compile(source, path, 'exec'), globals(), globals()) 
Example #16
Source File: local.py    From shadowsocks-with-socks-auth with Apache License 2.0 5 votes vote down vote up
def main():
    shell.check_python()

    # fix py2exe
    if hasattr(sys, "frozen") and sys.frozen in \
            ("windows_exe", "console_exe"):
        p = os.path.dirname(os.path.abspath(sys.executable))
        os.chdir(p)

    config = shell.get_config(True)

    daemon.daemon_exec(config)

    try:
        logging.info("starting local at %s:%d" %
                     (config['local_address'], config['local_port']))

        dns_resolver = asyncdns.DNSResolver()
        tcp_server = tcprelay.TCPRelay(config, dns_resolver, True)
        udp_server = udprelay.UDPRelay(config, dns_resolver, True)
        loop = eventloop.EventLoop()
        dns_resolver.add_to_loop(loop)
        tcp_server.add_to_loop(loop)
        udp_server.add_to_loop(loop)

        def handler(signum, _):
            logging.warn('received SIGQUIT, doing graceful shutting down..')
            tcp_server.close(next_tick=True)
            udp_server.close(next_tick=True)
        signal.signal(getattr(signal, 'SIGQUIT', signal.SIGTERM), handler)

        def int_handler(signum, _):
            sys.exit(1)
        signal.signal(signal.SIGINT, int_handler)

        daemon.set_user(config.get('user', None))
        loop.run()
    except Exception as e:
        shell.print_exception(e)
        sys.exit(1) 
Example #17
Source File: wrapper.py    From python-ovrsdk with Do What The F*ck You Want To Public License 5 votes vote down vote up
def getdirs(self,libname):
        '''Implements the dylib search as specified in Apple documentation:

        http://developer.apple.com/documentation/DeveloperTools/Conceptual/
            DynamicLibraries/Articles/DynamicLibraryUsageGuidelines.html

        Before commencing the standard search, the method first checks
        the bundle's ``Frameworks`` directory if the application is running
        within a bundle (OS X .app).
        '''

        dyld_fallback_library_path = _environ_path("DYLD_FALLBACK_LIBRARY_PATH")
        if not dyld_fallback_library_path:
            dyld_fallback_library_path = [os.path.expanduser('~/lib'),
                                          '/usr/local/lib', '/usr/lib']

        dirs = []

        if '/' in libname:
            dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))
        else:
            dirs.extend(_environ_path("LD_LIBRARY_PATH"))
            dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))

        dirs.extend(self.other_dirs)
        dirs.append(".")
        dirs.append(os.path.dirname(__file__))

        if hasattr(sys, 'frozen') and sys.frozen == 'macosx_app':
            dirs.append(os.path.join(
                os.environ['RESOURCEPATH'],
                '..',
                'Frameworks'))

        dirs.extend(dyld_fallback_library_path)

        return dirs

# Posix 
Example #18
Source File: test_utils.py    From geofront-cli with GNU General Public License v3.0 5 votes vote down vote up
def test_unfrozen_dev_toplevel_raises_nopath(self):
        """Not frozen, raise OSError when the path doesn't exist."""
        self.patch(os.path, "exists", lambda x: False)
        self.assertRaises(OSError, get_program_path, "foo") 
Example #19
Source File: test_utils.py    From geofront-cli with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        """SetUp to mimic frozen darwin."""
        super(DarwinPkgdTestCase, self).setUp()
        self.patch(sys, "platform", "darwin")
        sys.frozen = True

        self.darwin_app_names = {"foo": "Foo.app"} 
Example #20
Source File: test_utils.py    From geofront-cli with GNU General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        """tearDown, Remove frozen attr"""
        del sys.frozen
        super(DarwinPkgdTestCase, self).tearDown() 
Example #21
Source File: test_utils.py    From geofront-cli with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        """SetUp to mimic frozen windows."""
        super(Win32PkgdTestCase, self).setUp()
        self.patch(sys, "platform", "win32")
        sys.frozen = True 
Example #22
Source File: test_utils.py    From geofront-cli with GNU General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        """tearDown, Remove frozen attr"""
        del sys.frozen
        super(Win32PkgdTestCase, self).tearDown() 
Example #23
Source File: test_utils.py    From geofront-cli with GNU General Public License v3.0 5 votes vote down vote up
def test_windows_pkgd(self):
        """Return sub-app path on windows when frozen."""

        self.patch(sys, "executable", os.path.join("C:\\path", "to",
                                                   "current.exe"))
        # patch abspath to let us run this tests on non-windows:
        self.patch(os.path, "abspath", lambda x: x)
        path = get_program_path("foo", None)
        expectedpath = os.path.join("C:\\path", "to", "foo.exe")
        self.assertEquals(path, expectedpath) 
Example #24
Source File: applications.py    From zim-desktop-wiki with GNU General Public License v2.0 5 votes vote down vote up
def _main_is_frozen():
	# Detect whether we are running py2exe compiled version
	return hasattr(sys, 'frozen') and sys.frozen 
Example #25
Source File: libraryloader.py    From ctypesgen with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getdirs(self, libname):
        """Implements the dylib search as specified in Apple documentation:

        http://developer.apple.com/documentation/DeveloperTools/Conceptual/
            DynamicLibraries/Articles/DynamicLibraryUsageGuidelines.html

        Before commencing the standard search, the method first checks
        the bundle's ``Frameworks`` directory if the application is running
        within a bundle (OS X .app).
        """

        dyld_fallback_library_path = _environ_path("DYLD_FALLBACK_LIBRARY_PATH")
        if not dyld_fallback_library_path:
            dyld_fallback_library_path = [os.path.expanduser("~/lib"), "/usr/local/lib", "/usr/lib"]

        dirs = []

        if "/" in libname:
            dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))
        else:
            dirs.extend(_environ_path("LD_LIBRARY_PATH"))
            dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))

        if hasattr(sys, "frozen") and sys.frozen == "macosx_app":
            dirs.append(os.path.join(os.environ["RESOURCEPATH"], "..", "Frameworks"))

        dirs.extend(dyld_fallback_library_path)

        return dirs


# Posix 
Example #26
Source File: pydemolib.py    From ctypesgen with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getdirs(self, libname):
        """Implements the dylib search as specified in Apple documentation:

        http://developer.apple.com/documentation/DeveloperTools/Conceptual/
            DynamicLibraries/Articles/DynamicLibraryUsageGuidelines.html

        Before commencing the standard search, the method first checks
        the bundle's ``Frameworks`` directory if the application is running
        within a bundle (OS X .app).
        """

        dyld_fallback_library_path = _environ_path("DYLD_FALLBACK_LIBRARY_PATH")
        if not dyld_fallback_library_path:
            dyld_fallback_library_path = [os.path.expanduser("~/lib"), "/usr/local/lib", "/usr/lib"]

        dirs = []

        if "/" in libname:
            dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))
        else:
            dirs.extend(_environ_path("LD_LIBRARY_PATH"))
            dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))

        if hasattr(sys, "frozen") and sys.frozen == "macosx_app":
            dirs.append(os.path.join(os.environ["RESOURCEPATH"], "..", "Frameworks"))

        dirs.extend(dyld_fallback_library_path)

        return dirs


# Posix 
Example #27
Source File: quteprocess.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def _executable_args(self):
        profile = self.request.config.getoption('--qute-profile-subprocs')
        if hasattr(sys, 'frozen'):
            if profile:
                raise Exception("Can't profile with sys.frozen!")
            executable = os.path.join(os.path.dirname(sys.executable),
                                      'qutebrowser')
            args = []
        else:
            executable = sys.executable
            if profile:
                profile_dir = os.path.join(os.getcwd(), 'prof')
                profile_id = '{}_{}'.format(self._instance_id,
                                            next(self._run_counter))
                profile_file = os.path.join(profile_dir,
                                            '{}.pstats'.format(profile_id))
                try:
                    os.mkdir(profile_dir)
                except FileExistsError:
                    pass
                args = [os.path.join('scripts', 'dev', 'run_profile.py'),
                        '--profile-tool', 'none',
                        '--profile-file', profile_file]
            else:
                args = ['-bb', '-m', 'qutebrowser']
        return executable, args 
Example #28
Source File: test_path.py    From Computable with MIT License 5 votes vote down vote up
def test_get_home_dir_2():
    """Testcase for py2exe logic, compressed lib
    """
    unfrozen = path.get_home_dir()
    sys.frozen = True
    #fake filename for IPython.__init__
    IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower()

    home_dir = path.get_home_dir(True)
    nt.assert_equal(home_dir, unfrozen) 
Example #29
Source File: test_path.py    From Computable with MIT License 5 votes vote down vote up
def test_get_home_dir_1():
    """Testcase for py2exe logic, un-compressed lib
    """
    unfrozen = path.get_home_dir()
    sys.frozen = True

    #fake filename for IPython.__init__
    IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py"))

    home_dir = path.get_home_dir()
    nt.assert_equal(home_dir, unfrozen) 
Example #30
Source File: rabinpoly.py    From librabinpoly with GNU General Public License v2.0 5 votes vote down vote up
def getdirs(self,libname):
        '''Implements the dylib search as specified in Apple documentation:

        http://developer.apple.com/documentation/DeveloperTools/Conceptual/
            DynamicLibraries/Articles/DynamicLibraryUsageGuidelines.html

        Before commencing the standard search, the method first checks
        the bundle's ``Frameworks`` directory if the application is running
        within a bundle (OS X .app).
        '''

        dyld_fallback_library_path = _environ_path("DYLD_FALLBACK_LIBRARY_PATH")
        if not dyld_fallback_library_path:
            dyld_fallback_library_path = [os.path.expanduser('~/lib'),
                                          '/usr/local/lib', '/usr/lib']

        dirs = []

        if '/' in libname:
            dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))
        else:
            dirs.extend(_environ_path("LD_LIBRARY_PATH"))
            dirs.extend(_environ_path("DYLD_LIBRARY_PATH"))

        dirs.extend(self.other_dirs)
        dirs.append(".")
        dirs.append(os.path.dirname(__file__))

        if hasattr(sys, 'frozen') and sys.frozen == 'macosx_app':
            dirs.append(os.path.join(
                os.environ['RESOURCEPATH'],
                '..',
                'Frameworks'))

        dirs.extend(dyld_fallback_library_path)

        return dirs

# Posix