Python os.name() Examples

The following are 30 code examples for showing how to use os.name(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module os , or try the search function .

Example 1
Project: svviz   Author: svviz   File: utilities.py    License: MIT License 6 votes vote down vote up
def __init__(self, chr_, start, end, strand):
        """
        :param chr: chromosome name (string)
        :param strand: '+' or '-' (or '.' for an ambidexterous locus)
        :param start: start coordinate of the locus
        :param end: coord of the last nucleotide (inclusive) """
        coords = [start,end]
        coords.sort()
        # this method for assigning chromosome should help avoid storage of
        # redundant strings.
        self._chr = chr_
        self._strand = strand
        self._start = int(coords[0])
        self._end = int(coords[1])

        if self._start < 0:
            raise Exception("Locus start coordinate cannot be negative: {}".format(start)) 
Example 2
Project: gog-galaxy-plugin-downloader   Author: Slashbunny   File: download.py    License: GNU General Public License v3.0 6 votes vote down vote up
def process_template_strings(data):
    """
    Replaces $variables in strings with corresponding variables in plugin data
    """
    for plugin_name, plugin_data in data.items():
        version = plugin_data['version']
        guid = plugin_data['guid']

        for key, value in plugin_data.items():
            if key == 'version':
                continue
            if not isinstance(value, str):
                continue

            # Replace references to $name and $version with the real values
            data[plugin_name][key] = Template(value).substitute(
                                        name=plugin_name,
                                        version=version,
                                        guid=guid)

    return data 
Example 3
Project: vergeml   Author: mme   File: display.py    License: MIT License 6 votes vote down vote up
def __init__(self, conf, width=70, pad=4, left_align=set()):
        self.conf = conf
        self.data = {}
        self.width = width
        self.pad = pad
        self.left_align = left_align

        self.by_cat = {}
        self.cats = []
        self.titles = []

        for item in self.conf:
            self.by_cat.setdefault(item['category'], {})

            if not item['category'] in self.cats:
                self.cats.append(item['category'])

            if not item['title'] in self.titles:
                self.titles.append(item['title'])
            
            self.by_cat[item['category']][item['title']] = (item['name'], item['format']) 
Example 4
Project: vergeml   Author: mme   File: display.py    License: MIT License 6 votes vote down vote up
def getvalue(self):
        
        title_row = [""]
        title_row.extend(self.titles)
        cat_rows = []
       

        for cat in self.cats:
            row = [cat]
            for title in self.titles:
                name, fmt = self.by_cat[cat][title]
                if name in self.data:
                    value = self.data[name]
                    fmt = "{:" +  fmt.lstrip("{").rstrip("}").lstrip(":") + "}"
                    row.append(fmt.format(value))
                else:
                    row.append("-")
            cat_rows.append(row)
        
        data = [title_row] + cat_rows
      
        t = Table(data, left_align=self.left_align)
        return t.getvalue(fit=False) + "\n" 
Example 5
Project: godot-mono-builds   Author: godotengine   File: os_utils.py    License: MIT License 6 votes vote down vote up
def run_command(command, args=[], cwd=None, env=None, name='command'):
    def cmd_args_to_str(cmd_args):
        return ' '.join([arg if not ' ' in arg else '"%s"' % arg for arg in cmd_args])

    assert isinstance(command, str) and isinstance(args, list)
    args = [command] + args

    check_call_args = {}
    if cwd is not None:
        check_call_args['cwd'] = cwd
    if env is not None:
        check_call_args['env'] = env

    import subprocess
    try:
        print('Running command \'%s\': %s' % (name, subprocess.list2cmdline(args)))
        subprocess.check_call(args, **check_call_args)
        print('Command \'%s\' completed successfully' % name)
    except subprocess.CalledProcessError as e:
        raise BuildError('\'%s\' exited with error code: %s' % (name, e.returncode)) 
Example 6
Project: godot-mono-builds   Author: godotengine   File: os_utils.py    License: MIT License 6 votes vote down vote up
def find_executable(name) -> str:
    is_windows = os.name == 'nt'
    windows_exts = os.environ['PATHEXT'].split(ENV_PATH_SEP) if is_windows else None
    path_dirs = os.environ['PATH'].split(ENV_PATH_SEP)

    search_dirs = path_dirs + [os.getcwd()] # cwd is last in the list

    for dir in search_dirs:
        path = os.path.join(dir, name)

        if is_windows:
            for extension in windows_exts:
                path_with_ext = path + extension

                if os.path.isfile(path_with_ext) and os.access(path_with_ext, os.X_OK):
                    return path_with_ext
        else:
            if os.path.isfile(path) and os.access(path, os.X_OK):
                return path

    return '' 
Example 7
Project: cherrypy   Author: cherrypy   File: test_states.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_SIGTERM(self):
        'SIGTERM should shut down the server whether daemonized or not.'
        self._require_signal_and_kill('SIGTERM')

        # Spawn a normal, undaemonized process.
        p = helper.CPProcess(ssl=(self.scheme.lower() == 'https'))
        p.write_conf(
            extra='test_case_name: "test_SIGTERM"')
        p.start(imports='cherrypy.test._test_states_demo')
        # Send a SIGTERM
        os.kill(p.get_pid(), signal.SIGTERM)
        # This might hang if things aren't working right, but meh.
        p.join()

        if os.name in ['posix']:
            # Spawn a daemonized process and test again.
            p = helper.CPProcess(ssl=(self.scheme.lower() == 'https'),
                                 wait=True, daemonize=True)
            p.write_conf(
                extra='test_case_name: "test_SIGTERM_2"')
            p.start(imports='cherrypy.test._test_states_demo')
            # Send a SIGTERM
            os.kill(p.get_pid(), signal.SIGTERM)
            # This might hang if things aren't working right, but meh.
            p.join() 
Example 8
Project: FRIDA   Author: LCAV   File: mkl_fft.py    License: MIT License 6 votes vote down vote up
def load_libmkl():
    if os.name == 'posix':
        try:
            lib_mkl = os.getenv('LIBMKL')
            return _ctypes.cdll.LoadLibrary(lib_mkl)
        except:
            pass
        try:
            return _ctypes.cdll.LoadLibrary("libmkl_rt.dylib")
        except:
            raise ValueError('MKL Library not found')

    else:
        try:
            return _ctypes.cdll.LoadLibrary("mk2_rt.dll")
        except:
            raise ValueError('MKL Library not found') 
Example 9
Project: multibootusb   Author: mbusb   File: admin.py    License: GNU General Public License v2.0 6 votes vote down vote up
def isUserAdmin():
    """
    @return: True if the current user is an 'Admin' whatever that means
    (root on Unix), otherwise False.

    Warning: The inner function fails unless you have Windows XP SP2 or
    higher. The failure causes a traceback to be gen.loged and this
    function to return False.
    """

    if platform.system() == "Windows":
        import ctypes
        # WARNING: requires Windows XP SP2 or higher!
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            traceback.print_exc()
            gen.log("Admin check failed, assuming not an admin.")
            return False
    elif platform.system() == "Linux":
        return os.getuid() == 0
    else:
        raise RuntimeError("Unsupported operating system for this module: %s" % (os.name,)) 
Example 10
Project: CAMISIM   Author: CAMI-challenge   File: analysis_mg.py    License: Apache License 2.0 6 votes vote down vote up
def parse(self, line):
        lineArray = line.split()
        if len(lineArray) != 2:
            print '_MothurOutFileParser: wrong line', line
            return
        name = re.sub(r'^([0-9]+_[0-9]+)_[0-9]+_[0-9]+_[pr]+[0-2]$',r'\1', lineArray[0])
        tag = re.sub(r'^[0-9]+_[0-9]+_([0-9]+_[0-9]+_[pr]+[0-2])$',r'\1', lineArray[0])
        placementList = lineArray[1].replace('unclassified;', '').rsplit(';')
        if len(placementList) < 2:
            #print '_MothurOutFileParser: skip line', line
            return

        placement = placementList[-2]
        try:
            clade = int(re.sub('([0-9]+)\(.*', r'\1' , placement))
        except ValueError:
            return
        weight = float(re.sub('[0-9]+\(([0-9\.]+)\)', r'\1' , placement))

        entry = str(str(name) + '\t' + str(clade) + '\t' + str(weight) + '\t' + str(self.source) + '\t' + str(tag))
        if self.outBuffer.isEmpty():
            self.outBuffer.writeText(entry)
        else:
            self.outBuffer.writeText(str('\n' + entry)) 
Example 11
Project: pastebin-monitor   Author: fabiospampinato   File: pastebin_crawler.py    License: GNU General Public License v2.0 6 votes vote down vote up
def log ( self, message, is_bold=False, color='', log_time=True):
        prefix = ''
        suffix = ''

        if log_time:
            prefix += '[{:s}] '.format(get_timestamp())

        if os.name == 'posix':
            if is_bold:
                prefix += self.shell_mod['BOLD']
            prefix += self.shell_mod[color.upper()]

            suffix = self.shell_mod['RESET']

        message = prefix + message + suffix
        print ( message )
        sys.stdout.flush() 
Example 12
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: get_data.py    License: Apache License 2.0 6 votes vote down vote up
def get_cifar10(data_dir):
    if not os.path.isdir(data_dir):
        os.system("mkdir " + data_dir)
    cwd = os.path.abspath(os.getcwd())
    os.chdir(data_dir)
    if (not os.path.exists('train.rec')) or \
       (not os.path.exists('test.rec')) :
        import urllib, zipfile, glob
        dirname = os.getcwd()
        zippath = os.path.join(dirname, "cifar10.zip")
        urllib.urlretrieve("http://data.mxnet.io/mxnet/data/cifar10.zip", zippath)
        zf = zipfile.ZipFile(zippath, "r")
        zf.extractall()
        zf.close()
        os.remove(zippath)
        for f in glob.glob(os.path.join(dirname, "cifar", "*")):
            name = f.split(os.path.sep)[-1]
            os.rename(f, os.path.join(dirname, name))
        os.rmdir(os.path.join(dirname, "cifar"))
    os.chdir(cwd)

# data 
Example 13
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: lint.py    License: Apache License 2.0 6 votes vote down vote up
def get_header_guard_dmlc(filename):
    """Get Header Guard Convention for DMLC Projects.

    For headers in include, directly use the path
    For headers in src, use project name plus path

    Examples: with project-name = dmlc
        include/dmlc/timer.h -> DMLC_TIMTER_H_
        src/io/libsvm_parser.h -> DMLC_IO_LIBSVM_PARSER_H_
    """
    fileinfo = cpplint.FileInfo(filename)
    file_path_from_root = fileinfo.RepositoryName()
    inc_list = ['include', 'api', 'wrapper']

    if file_path_from_root.find('src/') != -1 and _HELPER.project_name is not None:
        idx = file_path_from_root.find('src/')
        file_path_from_root = _HELPER.project_name +  file_path_from_root[idx + 3:]
    else:
        for spath in inc_list:
            prefix = spath + os.sep
            if file_path_from_root.startswith(prefix):
                file_path_from_root = re.sub('^' + prefix, '', file_path_from_root)
                break
    return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_' 
Example 14
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: lint.py    License: Apache License 2.0 6 votes vote down vote up
def get_header_guard_dmlc(filename):
    """Get Header Guard Convention for DMLC Projects.
    For headers in include, directly use the path
    For headers in src, use project name plus path
    Examples: with project-name = dmlc
        include/dmlc/timer.h -> DMLC_TIMTER_H_
        src/io/libsvm_parser.h -> DMLC_IO_LIBSVM_PARSER_H_
    """
    fileinfo = cpplint.FileInfo(filename)
    file_path_from_root = fileinfo.RepositoryName()
    inc_list = ['include', 'api', 'wrapper']

    if file_path_from_root.find('src/') != -1 and _HELPER.project_name is not None:
        idx = file_path_from_root.find('src/')
        file_path_from_root = _HELPER.project_name +  file_path_from_root[idx + 3:]
    else:
        for spath in inc_list:
            prefix = spath + os.sep
            if file_path_from_root.startswith(prefix):
                file_path_from_root = re.sub('^' + prefix, '', file_path_from_root)
                break
    return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_' 
Example 15
Project: smbprotocol   Author: jborean93   File: test_smbclient_shutil.py    License: MIT License 6 votes vote down vote up
def test_rmtree(smb_share):
    mkdir("%s\\dir2" % smb_share)
    mkdir("%s\\dir2\\dir3" % smb_share)

    with open_file("%s\\dir2\\dir3\\file1" % smb_share, mode='w') as fd:
        fd.write(u"content")

    with open_file("%s\\dir2\\file2" % smb_share, mode='w') as fd:
        fd.write(u"content")

    if os.name == "nt" or os.environ.get('SMB_FORCE', False):
        # File symlink
        symlink("%s\\dir2\\file2" % smb_share, "%s\\dir2\\file3" % smb_share)
        symlink("missing", "%s\\dir2\\file3-broken" % smb_share)

        # Dir symlink
        symlink("%s\\dir2\\dir3" % smb_share, "%s\\dir2\\dir-link" % smb_share)
        symlink("missing", "%s\\dir2\\dir-link-broken" % smb_share, target_is_directory=True)

    assert exists("%s\\dir2" % smb_share) is True

    rmtree("%s\\dir2" % smb_share)

    assert exists("%s\\dir2" % smb_share) is False 
Example 16
Project: smbprotocol   Author: jborean93   File: test_smbclient_os.py    License: MIT License 6 votes vote down vote up
def test_scamdir_with_pattern(smb_share):
    for filename in ["file.txt", "file-test1.txt", "file-test1a.txt"]:
        with smbclient.open_file("%s\\%s" % (smb_share, filename), mode="w") as fd:
            fd.write(u"content")

    count = 0
    names = []
    for dir_entry in smbclient.scandir(smb_share, search_pattern="file-test*.txt"):
        names.append(dir_entry.name)
        count += 1

    assert count == 2
    assert "file-test1.txt" in names
    assert "file-test1a.txt" in names

    names = []
    for dir_entry in smbclient.scandir(smb_share, search_pattern="file-test?.txt"):
        names.append(dir_entry.name)

    assert names == ["file-test1.txt"] 
Example 17
Project: smbprotocol   Author: jborean93   File: test_smbclient_os.py    License: MIT License 6 votes vote down vote up
def test_scandir_with_symlink(smb_share):
    with smbclient.open_file("%s\\file.txt" % smb_share, mode='w') as fd:
        fd.write(u"content")
    smbclient.symlink("%s\\file.txt" % smb_share, "%s\\link.txt" % smb_share)

    smbclient.mkdir("%s\\dir" % smb_share)
    smbclient.symlink("%s\\dir" % smb_share, "%s\\link-dir" % smb_share, target_is_directory=True)

    for entry in smbclient.scandir(smb_share):
        # This is tested in other tests, we only care about symlinks.
        if entry.name in ['file.txt', 'dir']:
            continue

        assert entry.is_symlink()
        assert entry.is_dir(follow_symlinks=False) is False
        assert entry.is_file(follow_symlinks=False) is False

        if entry.name == 'link.txt':
            assert entry.is_dir() is False
            assert entry.is_file() is True
        else:
            assert entry.is_dir() is True
            assert entry.is_file() is False 
Example 18
Project: smbprotocol   Author: jborean93   File: test_smbclient_os.py    License: MIT License 6 votes vote down vote up
def test_walk_topdown(smb_share):
    smbclient.makedirs("%s\\dir1\\dir2\\dir3" % smb_share)

    for name in ["file1.txt", "dir1\\file2.txt", "dir1\\dir2\\file3.txt", "dir1\\dir2\\dir3\\file4.txt"]:
        with smbclient.open_file("%s\\%s" % (smb_share, name), mode='w') as fd:
            fd.write(u"content")

    scanned_files = []
    scanned_dirs = []
    for root, dirs, files in smbclient.walk(smb_share):
        scanned_dirs.append(dirs[0])

        # Test out removing a dir entry will affect the further walks.
        if files == ['file3.txt']:
            del dirs[0]
        scanned_files.append(files[0])

    assert scanned_files == ['file1.txt', 'file2.txt', 'file3.txt']
    assert scanned_dirs == ['dir1', 'dir2', 'dir3'] 
Example 19
Project: smbprotocol   Author: jborean93   File: test_smbclient_os.py    License: MIT License 6 votes vote down vote up
def test_walk_bottomup(smb_share):
    smbclient.makedirs("%s\\dir1\\dir2\\dir3" % smb_share)

    for name in ["file1.txt", "dir1\\file2.txt", "dir1\\dir2\\file3.txt", "dir1\\dir2\\dir3\\file4.txt"]:
        with smbclient.open_file("%s\\%s" % (smb_share, name), mode='w') as fd:
            fd.write(u"content")

    scanned_files = []
    scanned_dirs = []
    for root, dirs, files in smbclient.walk(smb_share, topdown=False):
        if dirs:
            scanned_dirs.append(dirs[0])
        scanned_files.append(files[0])

    assert scanned_files == ['file4.txt', 'file3.txt', 'file2.txt', 'file1.txt']
    assert scanned_dirs == ['dir3', 'dir2', 'dir1'] 
Example 20
Project: wuy   Author: manatlan   File: freeze.py    License: GNU General Public License v2.0 6 votes vote down vote up
def build(path,inConsole=False,addWeb=False):
    params=[path,"--noupx","--onefile"]

    if not inConsole:
        params.append( "--noconsole")
    
    web=os.path.join( os.path.dirname(path), "web" )
    if addWeb and os.path.isdir(web):
        sep = (os.name == 'nt') and ";" or ":"
        params.append("--add-data=%s%sweb" % (web,sep))

    temp=os.path.join(tempfile.gettempdir(),".build")
    params.append( "--workpath" )
    params.append( temp )

    params.append( "--distpath" )
    params.append( os.path.dirname(path) )

    print( "PYINSTALLER:",params )
    pyi.run( params ) 
Example 21
Project: quart   Author: pgjones   File: cli.py    License: MIT License 6 votes vote down vote up
def get_command(self, ctx: click.Context, name: str) -> click.Command:
        """Return the relevant command given the context and name.

        .. warning::

            This differs substantially from Flask in that it allows
            for the inbuilt commands to be overridden.
        """
        info = ctx.ensure_object(ScriptInfo)
        command = None
        try:
            command = info.load_app().cli.get_command(ctx, name)
        except NoAppException:
            pass
        if command is None:
            command = super().get_command(ctx, name)
        return command 
Example 22
Project: pyhanlp   Author: hankcs   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def write_config(root=None):
    if root and os.name == 'nt':
        root = root.replace('\\', '/')  # For Windows
    if root and platform.system().startswith('CYGWIN'):  # For cygwin
        if root.startswith('/usr/lib'):
            cygwin_root = os.popen('cygpath -w /').read().strip().replace('\\', '/')
            root = cygwin_root + root[len('/usr'):]
        elif STATIC_ROOT.startswith('/cygdrive'):
            driver = STATIC_ROOT.split('/')
            cygwin_driver = '/'.join(driver[:3])
            win_driver = driver[2].upper() + ':'
            root = root.replace(cygwin_driver, win_driver)
    content = []
    with open_(PATH_CONFIG, encoding='utf-8') as f:
        for line in f:
            if root:
                if line.startswith('root'):
                    line = 'root={}{}'.format(root, os.linesep)
            content.append(line)
    with open_(PATH_CONFIG, 'w', encoding='utf-8') as f:
        f.writelines(content) 
Example 23
Project: svviz   Author: svviz   File: utilities.py    License: MIT License 5 votes vote down vote up
def launchFile(filepath):
    if sys.platform.startswith('darwin'):
        subprocess.call(('open', filepath))
    elif os.name == 'nt':
        os.startfile(filepath)
    elif os.name == 'posix':
        subprocess.call(('xdg-open', filepath))


############################ String utilities ############################ 
Example 24
Project: gog-galaxy-plugin-downloader   Author: Slashbunny   File: download.py    License: GNU General Public License v3.0 5 votes vote down vote up
def list_plugins(plugin_data):
    """
    Outputs known plugins, along with whether or not they are marked as default
    """
    print('Available plugins:')

    for name, data in plugin_data.items():
        print(name, end='')

        if 'default' in data and data['default'] is True:
            print(' [default]')
        else:
            print() 
Example 25
Project: gog-galaxy-plugin-downloader   Author: Slashbunny   File: download.py    License: GNU General Public License v3.0 5 votes vote down vote up
def filter_plugins(plugin_data, selected_plugins):
    """
    Takes the full set of plugin data and filters out only the plugins the
    user selected.

    If the user did not specify a list of plugins, it enables all the default
    plugins
    """
    # No plugins selected- remove all plugins not marked as "default"
    if selected_plugins is None:
        for name, data in list(plugin_data.items()):
            if 'default' not in data or data['default'] is not True:
                del plugin_data[name]
    # Plugin list provided at the command line
    else:
        selected_plugins = selected_plugins.split(',')
        # Ensure each selected plugin actually exists to point out errors
        for name in selected_plugins:
            if name not in plugin_data.keys():
                print('ERROR: Unknown plugin specified: {}'.format(name))
                sys.exit(1)
        # Remove any plugin not matching the providedlist
        for name, data in list(plugin_data.items()):
            if name not in selected_plugins:
                del plugin_data[name]

    return plugin_data 
Example 26
Project: gog-galaxy-plugin-downloader   Author: Slashbunny   File: download.py    License: GNU General Public License v3.0 5 votes vote down vote up
def fix_plugin_directories(dest):
    """
    Loops through all folders in the output directory, reads the their manifest
    file, and renames the directory to the standard <platform>_<guid> format
    """
    # Loop through directories in the destination directory
    for existing_dir in os.listdir(dest):
        existing_path = os.path.join(dest, existing_dir)

        # Skip non-directories
        if not os.path.isdir(existing_path):
            continue

        try:
            with open(os.path.join(existing_path, 'manifest.json')) as m:
                data = json.load(m)
                platform = data['platform']
                guid = data['guid']

                # Close json file
                m.close()

                expected_dir = platform + '_' + guid
                expected_path = os.path.join(dest, expected_dir)

                if existing_path != expected_path:
                    print('NOTICE: Folder should be "{}", but it is named "{}"'
                          .format(expected_dir, existing_dir))

                    if os.path.isdir(expected_path):
                        print('NOTICE: Correct pathed plugin already exists,'
                              + ' deleting extra plugin')
                        shutil.rmtree(existing_path)
                    else:
                        print('NOTICE: Renaming folder to proper name')
                        shutil.move(existing_path, expected_path)
        except (FileNotFoundError, json.decoder.JSONDecodeError, KeyError):
            print('ERROR: Could not read plugin data from {} folder'
                  .format(existing_path)) 
Example 27
Project: gog-galaxy-plugin-downloader   Author: Slashbunny   File: download.py    License: GNU General Public License v3.0 5 votes vote down vote up
def delete_old_plugins(data, dest):
    """
    Deletes versions of plugins that don't match the yaml manifest. In theory
    this should only be older versions, but any version that doesn't match
    the yaml definition will be deleted

    This explicitly does not touch other directories that do not match the
    known plugin names.

    If the version doesn't match the yaml definition, the directory is removed
    """
    # Loop over each plugin
    for name, data in data.items():
        expected_plugin_dir = name + '_' + data['guid']

        # Loop through directories in the destination directory
        for item in os.listdir(dest):
            full_path = os.path.join(dest, item)

            # Skip non-directories
            if not os.path.isdir(full_path):
                continue

            # Skip directory names that are in the valid plugin directory array
            if item == expected_plugin_dir:
                continue

            # If any other directory begins with <plugin_name>_, delete it
            if item.startswith(name + '_'):
                print('Deleting wrong version "{}" from "{}"'
                      .format(item, dest))
                shutil.rmtree(full_path) 
Example 28
Project: RF-Monitor   Author: EarToEarOak   File: gui.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __set_icon(self):
        icon = load_icon('logo.png')
        self.SetIcon(icon)

        if os.name == 'nt':
            import ctypes
            appId = u'com.eartoearoak.0.0'
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(appId) 
Example 29
Project: cherrypy   Author: cherrypy   File: test_states.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_daemonize(self):
        if os.name not in ['posix']:
            return self.skip('skipped (not on posix) ')
        self.HOST = '127.0.0.1'
        self.PORT = 8081
        # Spawn the process and wait, when this returns, the original process
        # is finished.  If it daemonized properly, we should still be able
        # to access pages.
        p = helper.CPProcess(ssl=(self.scheme.lower() == 'https'),
                             wait=True, daemonize=True,
                             socket_host='127.0.0.1',
                             socket_port=8081)
        p.write_conf(
            extra='test_case_name: "test_daemonize"')
        p.start(imports='cherrypy.test._test_states_demo')
        try:
            # Just get the pid of the daemonization process.
            self.getPage('/pid')
            self.assertStatus(200)
            page_pid = int(self.body)
            self.assertEqual(page_pid, p.get_pid())
        finally:
            # Shut down the spawned process
            self.getPage('/exit')
        p.join()

        # Wait until here to test the exit code because we want to ensure
        # that we wait for the daemon to finish running before we fail.
        if p.exit_code != 0:
            self.fail('Daemonized parent process failed to exit cleanly.') 
Example 30
Project: cherrypy   Author: cherrypy   File: test_states.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_SIGHUP_daemonized(self):
        # When daemonized, SIGHUP should restart the server.
        try:
            from signal import SIGHUP
        except ImportError:
            return self.skip('skipped (no SIGHUP) ')

        if os.name not in ['posix']:
            return self.skip('skipped (not on posix) ')

        # Spawn the process and wait, when this returns, the original process
        # is finished.  If it daemonized properly, we should still be able
        # to access pages.
        p = helper.CPProcess(ssl=(self.scheme.lower() == 'https'),
                             wait=True, daemonize=True)
        p.write_conf(
            extra='test_case_name: "test_SIGHUP_daemonized"')
        p.start(imports='cherrypy.test._test_states_demo')

        pid = p.get_pid()
        try:
            # Send a SIGHUP
            os.kill(pid, SIGHUP)
            # Give the server some time to restart
            time.sleep(2)
            self.getPage('/pid')
            self.assertStatus(200)
            new_pid = int(self.body)
            self.assertNotEqual(new_pid, pid)
        finally:
            # Shut down the spawned process
            self.getPage('/exit')
        p.join()