sys._MEIPASS

Here are the examples of the python api sys._MEIPASS taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

50 Examples 7

Example 1

Project: raspmedia Source File: RaspMediaAllPlayersPanel.py
Function: resource_path
def resource_path(relative_path):
    global BASE_PATH
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = BASE_PATH
    #print "JOINING " + base_path + " WITH " + relative_path
    resPath = os.path.normcase(os.path.join(base_path, relative_path))
    #resPath = base_path + relative_path
    #print resPath
    return resPath

Example 2

Project: spimagine Source File: gui_utils.py
Function: abs_path
def absPath(myPath):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    import sys

    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
        logger.debug("found MEIPASS: %s "%os.path.join(base_path, os.path.basename(myPath)))

        return os.path.join(base_path, os.path.basename(myPath))
    except Exception:
        base_path = os.path.abspath(os.path.dirname(__file__))
        return os.path.join(base_path, myPath)

Example 3

Project: reddwall Source File: reddwall.py
	def __init__(self, parent):
		wx.TaskBarIcon.__init__(self)
		if getattr(sys, 'frozen', False):
			basedir = sys._MEIPASS
		else:
			basedir = os.path.dirname(__file__)
		ICON_PATH = os.path.join(basedir, "alien.png")
		self.SetIcon(wx.Icon(ICON_PATH, wx.BITMAP_TYPE_PNG), "alien")
		self.Bind(wx.EVT_MENU, parent.NextWallpaper, id=self.ID_NEW_OPTION)
		self.Bind(wx.EVT_MENU, parent.CreatePrefWindow, id=self.ID_PREF_OPTION)
		self.Bind(wx.EVT_MENU, parent.Quit, id=wx.ID_EXIT)

Example 4

Project: EventMonkey Source File: EventMonkey.py
Function: init
        def __init__(self, *args, **kw):
            if hasattr(sys, 'frozen'):
                # We have to set original _MEIPASS2 value from sys._MEIPASS
                # to get --onefile mode working.
                os.putenv('_MEIPASS2', sys._MEIPASS)
            try:
                super(_Popen, self).__init__(*args, **kw)
            finally:
                if hasattr(sys, 'frozen'):
                    # On some platforms (e.g. AIX) 'os.unsetenv()' is not
                    # available. In those cases we cannot delete the variable
                    # but only set it to the empty string. The bootloader
                    # can handle this case.
                    if hasattr(os, 'unsetenv'):
                        os.unsetenv('_MEIPASS2')
                    else:
                        os.putenv('_MEIPASS2', '')

Example 5

Project: bitmask_client Source File: __init__.py
Function: here
def here(module=None):
    if getattr(sys, 'frozen', False):
        # we are running in a |PyInstaller| bundle
        return sys._MEIPASS
    else:
        dirname = os.path.dirname
        if module:
            return dirname(module.__file__)
        else:
            return dirname(__file__)

Example 6

Project: kcc Source File: kcc.py
        def __init__(self, *args, **kw):
            if hasattr(sys, 'frozen'):
                # noinspection PyProtectedMember
                os.putenv('_MEIPASS2', sys._MEIPASS)
            try:
                super(_Popen, self).__init__(*args, **kw)
            finally:
                if hasattr(sys, 'frozen'):
                    if hasattr(os, 'unsetenv'):
                        os.unsetenv('_MEIPASS2')
                    else:
                        os.putenv('_MEIPASS2', '')

Example 7

Project: spimagine Source File: glwidget.py
Function: abs_path
def absPath(myPath):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
        return os.path.join(base_path, os.path.basename(myPath))
    except Exception:
        base_path = os.path.abspath(os.path.dirname(__file__))
        return os.path.join(base_path, myPath)

Example 8

Project: arkos-install Source File: Installer.py
Function: resource_path
def resource_path(relative_path):
    try:
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

Example 9

Project: photograbber Source File: res.py
Function: get_path
def getpath(name=None):
    if getattr(sys, '_MEIPASS', None):
        basedir = sys._MEIPASS
    else:
        #basedir = os.path.dirname(__file__)
        basedir = os.getcwd()
        
    if name is None:
        return basedir

    return os.path.join(basedir, name)

Example 10

Project: hindsight Source File: hindsightGUI.py
Function: resource_path
def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

Example 11

Project: grow Source File: utils.py
def is_packaged_app():
    try:
        sys._MEIPASS
        return True
    except AttributeError:
        return False

Example 12

Project: simp_le Source File: rthook-entrypoints.py
Function: main
def main():
    """Monkey-patch `pkg_resources` with correct database."""
    entry_points_path = os.path.join(sys._MEIPASS, 'entry_points.json')
    with open(entry_points_path) as fp:
        all_entry_points = json.loads(fp.read())
    patch(pkg_resources)(iter_entry_points_factory(all_entry_points))

Example 13

Project: Fastir_Collector Source File: main.py
Function: parse_config_file
def parse_config_file(config_file, param_options):
    """Parse config file specified in argument, or default config file (FastIR.conf)"""
    # If no config_file was specified, fallback to bundled config
    if not config_file:
        config_file = "FastIR.conf"
        # If app is frozen with pyinstaller, look for temporary file path
        if hasattr(sys, "frozen"):
            config_file = os.path.join(sys._MEIPASS, config_file)
    else:
        # If a config_file was specified but doesn"t exist, tell the user and quit
        if not os.path.isfile(config_file):
            sys.stderr.write("Error: config file '%s' not found" % config_file)
            sys.exit(1)

    if os.path.isfile(config_file):
        return profile_used(config_file, param_options)
    else:
        return {}

Example 14

Project: listen1 Source File: utils.py
Function: resource_path
def resource_path(relative):
    """ Gets the resource's absolute path.

    :param relative: the relative path to the resource file.
    :return: the absolute path to the resource file.
    """
    if hasattr(sys, "_MEIPASS"):
        return os.path.join(sys._MEIPASS, relative)

    abspath = os.path.abspath(os.path.join(__file__, ".."))
    abspath = os.path.dirname(abspath)
    return os.path.join(abspath, relative)

Example 15

Project: Fastir_Collector Source File: mem.py
Function: init
    def __init__(self, *args, **kw):
        if hasattr(sys, 'frozen'):
            # We have to set original _MEIPASS2 value from sys._MEIPASS
            # to get --onefile mode working.
            # Last character is stripped in C-loader. We have to add
            # '/' or '\\' at the end.
            os.putenv('_MEIPASS2', sys._MEIPASS + os.sep)
        try:
            super(_Popen, self).__init__(*args, **kw)
        finally:
            if hasattr(sys, 'frozen'):
                # On some platforms (e.g. AIX) 'os.unsetenv()' is not
                # available. In those cases we cannot delete the variable
                # but only set it to the empty string. The bootloader
                # can handle this case.
                if hasattr(os, 'unsetenv'):
                    os.unsetenv('_MEIPASS2')
                else:
                    os.putenv('_MEIPASS2', '')

Example 16

Project: spimagine Source File: loadcolormaps.py
Function: abs_path
def _absPath(myPath):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    import sys

    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
        logger.DEBUG("found MEIPASS: %s "%os.path.join(base_path, os.path.basename(myPath)))

        return os.path.join(base_path, os.path.basename(myPath))
    except Exception:
        base_path = os.path.abspath(os.path.dirname(__file__))
        return os.path.join(base_path, myPath)

Example 17

Project: spimagine Source File: loadcolormaps.py
def loadcolormaps():
    cmaps = {}

    try:
        basePath = sys._MEIPASS
    except:
        basePath = _absPath("../colormaps/")

    reg = re.compile("cmap_(.*)\.png")
    for fName in os.listdir(basePath):
        match = reg.match(fName)
        if match:
            try:
                cmaps[match.group(1)] = _arrayFromImage(os.path.join(basePath,fName))[0,:,:]
            except Exception as e:
                print e
                print "could not load %s"%fName

    return cmaps

Example 18

Project: spimagine Source File: imageprocessor_view.py
Function: abs_path
def absPath(myPath):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    import os
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
        return os.path.join(base_path, os.path.basename(myPath))
    except Exception:
        base_path = os.path.abspath(os.path.dirname(__file__))
        return os.path.join(base_path, myPath)

Example 19

Project: spimagine Source File: spimagine_gui.py
Function: abs_path
def absPath(myPath):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    import sys

    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
        logger.debug("found MEIPASS: %s "%os.path.join(base_path, os.path.basename(myPath)))

        return os.path.join(base_path, os.path.basename(myPath))
    except Exception as e:
        logger.debug("did not find MEIPASS: %s "%e)


        base_path = os.path.abspath(os.path.dirname(__file__))
        return os.path.join(base_path, myPath)

Example 20

Project: memsql-loader Source File: setuser.py
def __fix_perms(userinfo):
    """ If _MEIPASS is defined we are executing in a pyinstaller environment
    In that case we need to recursively chown that directory to our target user before continuing.
    """
    try:
        # we can't check to see if this exists since it is set weirdly
        target = sys._MEIPASS
    except:
        return

    # try to use the chown command, if that fails then we fallback to python
    try:
        with open('/dev/null', 'wb') as devnull:
            subprocess.check_call(['chown', '-R', '%s:%s' % (userinfo.pw_uid, userinfo.pw_gid), target], stdout=devnull, stderr=devnull)
    except (OSError, subprocess.CalledProcessError):
        os.chown(target, userinfo.pw_uid, userinfo.pw_gid)
        for root, dirs, files in os.walk(target):
            for f in itertools.chain(dirs, files):
                os.chown(os.path.join(root, f), userinfo.pw_uid, userinfo.pw_gid)

Example 21

Project: aeneas Source File: globalfunctions.py
def bundle_directory():
    """
    Return the absolute path of the bundle directory
    if running from a frozen binary; otherwise return ``None``.

    :rtype: string
    """
    if FROZEN:
        return sys._MEIPASS
    return None

Example 22

Project: eavatar-me Source File: misc.py
Function: base_path
def base_path():
    if hasattr(sys, "_MEIPASS"):
        return sys._MEIPASS
    else:
        # assumes this file is located at src/ava/util/__init__.py
        abspath = os.path.abspath(os.path.join(__file__, "..", ".."))
        abspath = os.path.dirname(abspath)
        return abspath

Example 23

Project: spimagine Source File: keyframe_view.py
Function: abs_path
def absPath(myPath):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    import sys

    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
        logger.debug("found MEIPASS: %s "%os.path.join(base_path, os.path.basename(myPath)))

        return os.path.join(base_path, os.path.basename(myPath))
    except Exception:

        base_path = os.path.abspath(os.path.dirname(__file__))
        logger.debug("didnt found MEIPASS...: %s "%os.path.join(base_path, myPath))

        return os.path.join(base_path, myPath)

Example 24

Project: eavatar-me Source File: misc.py
Function: resource_path
def resource_path(relative):
    if hasattr(sys, "_MEIPASS"):
        return os.path.join(sys._MEIPASS, relative)

    abspath = os.path.abspath(os.path.join(__file__, "..", ".."))
    abspath = os.path.dirname(abspath)
    return os.path.join(abspath, relative)

Example 25

Project: mastermind Source File: cli.py
def simple_mode(config):
    if not ("response-body" in config["core"] and "url" in config["core"]):
        return Exception("Simple mode requires response-body and url flags")

    script_path_template = "{}/scripts/simple.py {} {}"
    script_path = os.path.dirname(os.path.realpath(__file__))

    if getattr(sys, 'frozen', False):
        script_path = sys._MEIPASS

    script_arg = ["--script",
                  script_path_template.format(script_path,
                                              config["core"]["url"],
                                              config["core"]["response-body"])]

    return common_args(config) + script_arg + verbosity_args(config)

Example 26

Project: SWProxy Source File: SWProxy.py
Function: resource_path
def resource_path(relative_path):
    # function to locate data files for pyinstaller single file executable
    # ref: http://stackoverflow.com/a/32048136
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)

    return os.path.join(os.path.abspath("."), relative_path)

Example 27

Project: raspmedia Source File: RaspMediaControlPanel.py
Function: resource_path
def resource_path(relative_path):
    global BASE_PATH
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = BASE_PATH
    resPath = os.path.normcase(os.path.join(base_path, relative_path))
    #resPath = base_path + relative_path
    #print resPath
    return resPath

Example 28

Project: pypdfocr Source File: pypdfocr_multiprocessing.py
    def __init__(self, *args, **kw):
        if hasattr(sys, 'frozen'):
            # We have to set original _MEIPASS2 value from sys._MEIPASS
            # to get --onefile mode working.
            os.putenv('_MEIPASS2', sys._MEIPASS)
        try:
            super(_Popen, self).__init__(*args, **kw)
        finally:
            if hasattr(sys, 'frozen'):
                # On some platforms (e.g. AIX) 'os.unsetenv()' is not
                # available. In those cases we cannot delete the variable
                # but only set it to the empty string. The bootloader
                # can handle this case.
                if hasattr(os, 'unsetenv'):
                    os.unsetenv('_MEIPASS2')
                else:
                    os.putenv('_MEIPASS2', '')

Example 29

Project: PyBitmessage Source File: shared.py
def codePath():
    if frozen == "macosx_app":
        codePath = os.environ.get("RESOURCEPATH")
    elif frozen: # windows
        codePath = sys._MEIPASS
    else:    
        codePath = os.path.dirname(__file__)
    return codePath

Example 30

Project: CIS-ESP Source File: support.py
Function: resource_path
def resource_path(relative_path, try_temp_path=True):
	""" Get absolute path to resource, works for dev and for PyInstaller """
	if try_temp_path:
		try:
			# PyInstaller creates a temp folder and stores path in _MEIPASS
			base_path = sys._MEIPASS
		except Exception:
			base_path = os.path.abspath(".")
	else:
		base_path = os.path.abspath(".")
		
	return os.path.join(base_path, relative_path)

Example 31

Project: padpyght Source File: __main__.py
def list_skin_paths():
    if getattr(sys, 'frozen', False):
        base_dir = os.path.join(sys._MEIPASS, 'padpyght', 'skins')
        for dir_name in os.listdir(base_dir):
            path = os.path.join(base_dir, dir_name)
            yield dir_name, path
    else:
        for dir_name in pkg_resources.resource_listdir('padpyght', 'skins'):
            path = pkg_resources.resource_filename('padpyght',
                                                   'skins/%s' % dir_name)
            yield dir_name, path

Example 32

Project: detekt Source File: utils.py
Function: get_resource
def get_resource(relative):
    # First try from the local directory. This might come handy in case we want
    # to provide updates or allow the user to run custom signatures.
    path = os.path.join(os.getcwd(), relative)
    # In case the resource doesn't exist in the current directory, we'll try
    # from the actual resources.
    if not os.path.exists(path):
        if hasattr(sys, '_MEIPASS'):
            path = os.path.join(sys._MEIPASS, relative)

    return path

Example 33

Project: fallingsky Source File: util.py
Function: here
def _here():
    """Returns the current full directory path."""

    if hasattr(sys, "_MEIPASS"):  # pyinstaller deployed
        return os.path.join(sys._MEIPASS)
    else:
        return os.path.dirname(os.path.realpath(__file__))

Example 34

Project: tatlin Source File: tatlin.py
Function: resolve_path
def resolve_path(fpath):
    if os.path.isabs(fpath):
        return fpath

    if getattr(sys, 'frozen', False):
        # we are running in a PyInstaller bundle
        basedir = sys._MEIPASS
    else:
        # we are running in a normal Python environment
        basedir = os.path.dirname(__file__)

    return os.path.join(basedir, fpath)

Example 35

Project: libturpial Source File: http.py
Function: init
    def __init__(self, base_url, proxies=None, timeout=None):
        self.base_url = base_url
        self.proxies = proxies or {}
        self.timeout = timeout or DEFAULT_TIMEOUT

        self.log = logging.getLogger('TurpialHTTP')

        try:
            # if getattr(sys, 'frozen', None):
            basedir = sys._MEIPASS
            self.ca_certs_file = os.path.realpath(os.path.join(basedir,
                                                               'cacert.pem'))
            # else:
        except:
            basedir = os.path.dirname(__file__)
            self.ca_certs_file = os.path.realpath(os.path.join(basedir,
                                                  '..', 'certs',
                                                  'cacert.pem'))

Example 36

Project: raspmedia Source File: AppFrame.py
Function: resource_path
def resource_path(relative_path):
    global BASE_PATH
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
        #print "BASE PATH FOUND: "+ base_path
    except Exception:
        #print "BASE PATH NOT FOUND!"
        base_path = BASE_PATH
    #print "JOINING " + base_path + " WITH " + relative_path
    resPath = os.path.normcase(os.path.join(base_path, relative_path))
    #resPath = base_path + relative_path
    #print resPath
    return resPath

Example 37

Project: pyocr Source File: tesseract.py
Function: set_environment
def _set_environment():
    if getattr(sys, 'frozen', False):
        # Pyinstaller support
        path = os.environ["PATH"]
        if sys._MEIPASS in path:
            # already changed
            return

        tesspath = os.path.join(sys._MEIPASS, "tesseract")
        tessprefix = os.path.join(sys._MEIPASS, "data")
        logger.info("Running in packaged environment")

        if not os.path.exists(os.path.join(tessprefix, "tessdata")):
            logger.warning(
                "Running from container, but no tessdata ({}) found !".format(tessprefix)
            )
        else:
            logger.info("TESSDATA_PREFIX set to [{}]".format(tessprefix))
            os.environ['TESSDATA_PREFIX'] = tessprefix
        if not os.path.exists(tesspath):
            logger.warning(
                "Running from container, but no tesseract ({}) found !".format(tesspath)
            )
        else:
            logger.info("[{}] added to PATH".format(tesspath))
            os.environ['PATH'] = (
                tesspath + os.pathsep + os.environ['PATH']
            )

Example 38

Project: RaceCapture_App Source File: main.py
    def __init__(self, **kwargs):
        super(RaceCaptureApp, self).__init__(**kwargs)

        if kivy.platform == 'ios' or kivy.platform == 'macosx':
            kivy.resources.resource_add_path(os.path.join(os.path.dirname(os.path.realpath(__file__)), "data"))

        # We do this because when this app is bundled into a standalone app
        # by pyinstaller we must reference all files by their absolute paths
        # sys._MEIPASS is provided by pyinstaller
        if getattr(sys, 'frozen', False):
            self.base_dir = sys._MEIPASS
        else:
            self.base_dir = os.path.dirname(os.path.abspath(__file__))

        self.settings = SystemSettings(self.user_data_dir, base_dir=self.base_dir)
        self.trackManager = TrackManager(user_dir=self.settings.get_default_data_dir(), base_dir=self.base_dir)

        # RaceCapture communications API
        self._rc_api = RcpApi(on_disconnect=self._on_rcp_disconnect, settings=self.settings)

        self._databus = DataBusFactory().create_standard_databus(self.settings.systemChannels)
        self.settings.runtimeChannels.data_bus = self._databus
        self._datastore = DataStore(databus=self._databus)
        self._session_recorder = SessionRecorder(self._datastore, self._databus, self._rc_api, self.settings, self.trackManager)
        self._session_recorder.bind(on_recording=self._on_session_recording)


        HelpInfo.settings = self.settings

        # Ensure soft input mode text inputs aren't obstructed
        Window.softinput_mode = 'below_target'

        # Capture keyboard events for handling escape / back
        Window.bind(on_keyboard=self._on_keyboard)

        self.register_event_type('on_tracks_updated')
        self.processArgs()
        self.settings.appConfig.setUserDir(self.user_data_dir)
        self.setup_telemetry()

Example 39

Project: bitmask_client Source File: pix.py
def start_pixelated_user_agent(userid, soledad, keymanager):

    leap_session = LeapSessionAdapter(
        userid, soledad, keymanager)

    config = Config()
    leap_home = os.path.join(get_path_prefix(), 'leap')
    config.leap_home = leap_home
    leap_session.config = config

    services_factory = SingleUserServicesFactory(
        UserAgentMode(is_single_user=True))

    if getattr(sys, 'frozen', False):
        # we are running in a |PyInstaller| bundle
        static_folder = os.path.join(sys._MEIPASS, 'pixelated_www')
    else:
        static_folder = os.path.abspath(pixelated_www.__path__[0])

    resource = RootResource(services_factory, static_folder=static_folder)

    config.host = 'localhost'
    config.port = 9090
    config.sslkey = None
    config.sslcert = None

    d = leap_session.account.callWhenReady(
        lambda _: _start_in_single_user_mode(
            leap_session, config,
            resource, services_factory))
    return d

Example 40

Project: Fastir_Collector Source File: utils.py
def create_driver_service(logger):
    """Creates the service for winpmem"""
    # Must have absolute path here.
    if hasattr(sys, "frozen"):
        driver = os.path.join(sys._MEIPASS, get_winpmem_name())
    else:
        driver = os.path.join(os.getcwd(), get_winpmem_name())

    h_scm = win32service.OpenSCManager(
            None, None, win32service.SC_MANAGER_CREATE_SERVICE)

    try:
        h_svc = win32service.CreateService(
                h_scm, "pmem", "pmem",
                win32service.SERVICE_ALL_ACCESS,
                win32service.SERVICE_KERNEL_DRIVER,
                win32service.SERVICE_DEMAND_START,
                win32service.SERVICE_ERROR_IGNORE,
                driver,
                None, 0, None, None, None)
    except win32service.error, e:
        logger.error(e)
        h_svc = win32service.OpenService(h_scm, "pmem",
                                         win32service.SERVICE_ALL_ACCESS)
    return h_svc

Example 41

Project: electrum-dash Source File: mnemonic.py
    def __init__(self, lang=None):
        if lang in [None, '']:
            lang = i18n.language.info().get('language', 'en')
        print_error('language', lang)
        filename = filenames.get(lang[0:2], 'english.txt')
        if getattr( sys, 'frozen' , None):
             path = os.path.join(sys._MEIPASS + "/lib/wordlist", filename)
        else: 
             path = os.path.join(os.path.dirname(__file__), 'wordlist', filename)
        s = open(path,'r').read().strip()
        s = unicodedata.normalize('NFKD', s.decode('utf8'))
        lines = s.split('\n')
        self.wordlist = []
        for line in lines:
            line = line.split('#')[0]
            line = line.strip(' \r')
            assert ' ' not in line
            if line:
                self.wordlist.append(line)
        print_error("wordlist has %d words"%len(self.wordlist))

Example 42

Project: Cryptully Source File: utils.py
Function: get_absolute_resource_path
def getAbsoluteResourcePath(relativePath):
    try:
        # PyInstaller stores data files in a tmp folder refered to as _MEIPASS
        basePath = sys._MEIPASS
    except Exception:
        # If not running as a PyInstaller created binary, try to find the data file as
        # an installed Python egg
        try:
            basePath = os.path.dirname(sys.modules['src'].__file__)
        except Exception:
            basePath = ''

        # If the egg path does not exist, assume we're running as non-packaged
        if not os.path.exists(os.path.join(basePath, relativePath)):
            basePath = 'src'

    path = os.path.join(basePath, relativePath)

    # If the path still doesn't exist, this function won't help you
    if not os.path.exists(path):
        return None

    return path

Example 43

Project: lighter Source File: util.py
Function: open_request
def openRequest(request, timeout=None):
    cafile = os.path.join(sys._MEIPASS, 'requests', 'cacert.pem') if getattr(sys, 'frozen', None) else None
    return urllib2.urlopen(request, cafile=cafile, timeout=timeout)

Example 44

Project: omnivore Source File: __init__.py
Function: get_image_path
def get_image_path(rel_path, module=None, file=None, up_one_level=False, excludes=[]):
    """Get the image path for static images relative to the specified module
    or file.
    
    The image path will be modified to find images in py2exe/py2app
    locations assuming that the data files have been added using the above
    get_py2exe_data_files function.
    
    Either the module or file keyword parameter may be specified to provide
    a relative module or file name.  The module may be specified either by
    reference to an imported module, or by a dotted string.  The file must be
    specified using the __file__ keyword.  If both are specified, file takes
    precedence.
    
    For example, in omnivore, the images are located in a directory "icons" in
    main omnivore directory (e.g. omnivore/icons):
        
    import omnivore
    image_path = get_image_path("icons", omnivore)
    
    will return the absolute path of "omnivore/icons".
    
    An example using the file keyword: if the current module is in the
    omnivore/framework directory, then the call to:
    
    get_image_path("icons", file=__file__)
    
    will contain the absolute path to the omnivore/framework/icons directory.
    """
    if file is None:
        if module is None:
            path = __file__
        else:
            try:
                path = module.__file__
            except AttributeError:
                # must be a string containing the module hiearchy
                path = module.replace(".", "/") + "/this-will-be-removed.py"
    else:
        path = file.replace(".", "/")
    import os
    import sys
    if up_one_level:
        path = os.path.dirname(path)
    frozen = getattr(sys, 'frozen', False)
    image_path = os.path.join(os.path.dirname(path), rel_path)
    if frozen:
        if frozen == True:
            # pyinstaller sets frozen=True and uses sys._MEIPASS
            root = sys._MEIPASS
            image_path = os.path.join(root, image_path)
        elif frozen in ('macosx_app'):
            #print "FROZEN!!! %s" % frozen
            root = os.environ['RESOURCEPATH']
            if ".zip/" in image_path:
                zippath, image_path = image_path.split(".zip/")
            image_path = os.path.join(root, image_path)
        else:
            print "App packager %s not yet supported for image paths!!!"
    return image_path

Example 45

Project: PennState-ACM-Check-in Source File: Utils.py
Function: get_absolute_resource_path
def getAbsoluteResourcePath(relativePath):
    try:
        # PyInstaller stores data files in a tmp folder refered to as _MEIPASS
        basePath = sys._MEIPASS
    except Exception:
        # If not running as a PyInstaller created binary, try to find the data file as
        # an installed Python egg
        try:
            basePath = os.path.dirname(sys.modules[''].__file__)
        except Exception:
            basePath = ''

        # If the egg path does not exist, assume we're running as non-packaged
        if not os.path.exists(os.path.join(basePath, relativePath)):
            basePath = ''

    path = os.path.join(basePath, relativePath)

    # If the path still doesn't exist, this function won't help you
    if not os.path.exists(path):
        return None

    return path

Example 46

Project: gdc-client Source File: client.py
Function: init
    def __init__(self, token, processes, server, part_size,
                 multipart=True, debug=False,
                 files={}, verify=True, manifest_name=None):
        self.headers = {'X-Auth-Token': token.strip()}
        self.manifest_name = manifest_name
        self.verify = verify
        try:
            # this only works in executable built by pyinstaller
            self.verify = os.path.join(
                sys._MEIPASS, 'requests', 'cacert.pem') if verify else verify
        except:
            print 'Using system default CA'

        self.files = files
        self.incompleted = deque(copy.deepcopy(self.files))
        self.server = server
        self.multipart = multipart
        self.upload_id = None
        self.debug = debug
        self.processes = processes
        self.part_size = (max(part_size, MIN_PARTSIZE)/PAGESIZE+1)*PAGESIZE
        self._metadata = None
        self.resume_path = "resume_{}".format(self.manifest_name)

Example 47

Project: grow Source File: utils.py
def get_grow_dir():
    if is_packaged_app():
        return os.path.join(sys._MEIPASS)
    return os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))

Example 48

Project: py12306 Source File: pyi_rth_usb.py
def get_load_func(type, candidates):
    def _load_library():
        exec_path = sys._MEIPASS

        l = None
        for candidate in candidates:
            # Do linker's path lookup work to force load bundled copy.
            if os.name == 'posix' and sys.platform == 'darwin':
                libs = glob.glob("%s/%s*.dylib*" % (exec_path, candidate))
            elif sys.platform == 'win32' or sys.platform == 'cygwin':
                libs = glob.glob("%s\\%s*.dll" % (exec_path, candidate))
            else:
                libs = glob.glob("%s/%s*.so*" % (exec_path, candidate))
            for libname in libs:
                try:
                    # NOTE: libusb01 is using CDLL under win32.
                    # (see usb.backends.libusb01)
                    if sys.platform == 'win32' and type != 'libusb01':
                        l = ctypes.WinDLL(libname)
                    else:
                        l = ctypes.CDLL(libname)
                    if l is not None:
                        break
                except:
                    l = None
            if l is not None:
                break
        else:
            raise OSError('USB library could not be found')

        if type == 'libusb10':
            if not hasattr(l, 'libusb_init'):
                raise OSError('USB library could not be found')
        return l
    return _load_library

Example 49

Project: mastermind Source File: cli.py
def driver_mode(config):
    if bool([x for x
            in ["script", "response-body", "url"]
            if x in config["core"].keys()]):

        return Exception("""The Driver mode does not allow a
                            script, a response body or a URL.""")

    config["core"]["storage-dir"] = storage_path()

    if not os.path.isdir(storage_path()):
        os.makedirs(storage_path())

    script_path_template = "{}/scripts/flasked.py {} {} {} {}"
    script_path = os.path.dirname(os.path.realpath(__file__))
    if getattr(sys, 'frozen', False):
        script_path = sys._MEIPASS

    script_arg = ["--script",
                  script_path_template.format(script_path,
                                              config["core"]["source-dir"],
                                              config["core"]["storage-dir"],
                                              config["core"]["host"],
                                              config["core"]["port"])]

    return common_args(config) + script_arg + verbosity_args(config)

Example 50

Project: cider Source File: util.py
Function: get_base_path
def get_base_path():
    """Find the path to the base of the executing service.

    This should be used for all path manipulation to ensure file paths from
    within the source tree of the application are found consistently in both
    frozen and normal execution mode.
    """
    if getattr(sys, 'frozen', False):
        # We are running in a PyInstaller bundle.
        logging.debug(
            'Running in compiled mode. Base directory is: %s' % sys._MEIPASS
        )
        return sys._MEIPASS
    else:
        # We are running in a normal Python environment.
        base_path = os.path.dirname(inspect.getfile(inspect.currentframe()))
        logging.debug(
            'Running in source mode. Base directory is: %s' % base_path
        )
        return base_path