Python os.nice() Examples

The following are code examples for showing how to use os.nice(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: whatstyle   Author: mikr   File: whatstyle.py    (MIT License) View Source Project 6 votes vote down vote up
def per_process_init():
    # type: () -> None
    try:
        os.nice(19)
    except AttributeError:
        # nice is not available everywhere.
        pass
    except OSError:
        # When this program is already running on the nicest level (20) on OS X
        # it is not permitted to change the priority.
        pass
    # A keyboard interrupt disrupts the communication between a
    # Python script and its subprocesses when using multiprocessing.
    # The child can ignore SIGINT and is properly shut down
    # by a pool.terminate() call in case of a keyboard interrupt
    # or an early generator exit.
    signal.signal(signal.SIGINT, signal.SIG_IGN) 
Example 2
Project: n1mm_view   Author: n1kdo   File: dashboard.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def update_charts(q, event, size):
    try:
        os.nice(10)
    except AttributeError:
        logging.warn("can't be nice to windows")
    q.put((CRAWL_MESSAGE, 4, 'Chart engine starting...'))
    base_map = graphics.create_map()
    last_qso_timestamp = 0
    q.put((CRAWL_MESSAGE, 4, ''))

    try:
        while not event.is_set():
            t0 = time.time()
            last_qso_timestamp = load_data(size, q, base_map, last_qso_timestamp)
            t1 = time.time()
            delta = t1 - t0
            update_delay = config.DATA_DWELL_TIME - delta
            if update_delay < 0:
                update_delay = config.DATA_DWELL_TIME
            logging.debug('Next data update in %f seconds', update_delay)
            event.wait(update_delay)
    except Exception, e:
        logging.exception('Exception in update_charts', exc_info=e)
        q.put((CRAWL_MESSAGE, 4, 'Chart engine failed.', graphics.YELLOW, graphics.RED)) 
Example 3
Project: pytrip   Author: pytrip   File: paths.py    (license) View Source Project 6 votes vote down vote up
def calculate_angle_quality_thread(self,
                                       voi,
                                       gantry,
                                       couch,
                                       calculate_from=0,
                                       stepsize=1.0,
                                       q=None,
                                       avoid=[],
                                       voi_cube=None,
                                       gradient=True):
        """ TODO: Documentation
        """
        os.nice(1)
        for couch_angle in couch:
            qual = self.calculate_angle_quality(voi, gantry, couch_angle, calculate_from, stepsize, avoid, voi_cube,
                                                gradient)
            q.put({"couch": couch_angle, "gantry": gantry, "data": qual}) 
Example 4
Project: isar   Author: ilbers   File: cooker.py    (license) View Source Project 6 votes vote down vote up
def parseConfiguration(self):
        # Set log file verbosity
        verboselogs = bb.utils.to_boolean(self.data.getVar("BB_VERBOSE_LOGS", False))
        if verboselogs:
            bb.msg.loggerVerboseLogs = True

        # Change nice level if we're asked to
        nice = self.data.getVar("BB_NICE_LEVEL", True)
        if nice:
            curnice = os.nice(0)
            nice = int(nice) - curnice
            buildlog.verbose("Renice to %s " % os.nice(nice))

        if self.recipecaches:
            del self.recipecaches
        self.multiconfigs = self.databuilder.mcdata.keys()
        self.recipecaches = {}
        for mc in self.multiconfigs:
            self.recipecaches[mc] = bb.cache.CacheData(self.caches_array)

        self.handleCollections(self.data.getVar("BBFILE_COLLECTIONS", True)) 
Example 5
Project: execnet   Author: pytest-dev   File: test_xspec.py    (license) View Source Project 6 votes vote down vote up
def test_norm_attributes(self):
        spec = XSpec("socket=192.168.102.2:8888//python=c:/this/python2.5"
                     "//chdir=d:\hello")
        assert spec.socket == "192.168.102.2:8888"
        assert spec.python == "c:/this/python2.5"
        assert spec.chdir == "d:\hello"
        assert spec.nice is None
        assert not hasattr(spec, '_xyz')

        pytest.raises(AttributeError, "spec._hello")

        spec = XSpec("socket=192.168.102.2:8888//python=python2.5//nice=3")
        assert spec.socket == "192.168.102.2:8888"
        assert spec.python == "python2.5"
        assert spec.chdir is None
        assert spec.nice == "3"

        spec = XSpec("[email protected]"
                     "//chdir=/hello/this//python=/usr/bin/python2.5")
        assert spec.ssh == "[email protected]"
        assert spec.python == "/usr/bin/python2.5"
        assert spec.chdir == "/hello/this"

        spec = XSpec("popen")
        assert spec.popen is True 
Example 6
Project: Nanopore-read-processor   Author: rrwick   File: process_reads.py    (license) View Source Project 6 votes vote down vote up
def make_ggplot_figures(self):
        info_filename = self.get_tsv_path()
        if not os.path.isfile(info_filename):
            print('Could not find tsv file: ' + info_filename)
            return

        r_script = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                'nanopore_read_analysis.R')
        print()
        print(' '.join(['nanopore_read_analysis.R', info_filename]), flush=True)
        command = [r_script, info_filename]
        p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             preexec_fn=lambda: os.nice(20))
        out, err = p.communicate()
        p.wait()
        script_output_lines = err.decode().splitlines()
        for line in script_output_lines:
            print('  ' + line) 
Example 7
Project: jack   Author: jack-cli-cd-ripper   File: workers.py    (license) View Source Project 6 votes vote down vote up
def start_new_process(args, nice_value=0):
    "start a new process in a pty and renice it"
    data = {}
    data['start_time'] = time.time()
    pid, master_fd = pty.fork()
    if pid == CHILD:
        default_signals()
        if nice_value:
            os.nice(nice_value)
        os.execvp(args[0], [a.encode(cf['_charset'], "replace") for a in args])
    else:
        data['pid'] = pid
        if os.uname()[0] == "Linux":
            fcntl.fcntl(master_fd, F_SETFL, O_NONBLOCK)
        data['fd'] = master_fd
        data['file'] = os.fdopen(master_fd)
        data['cmd'] = args
        data['buf'] = ""
        data['otf'] = 0
        data['percent'] = 0
        data['elapsed'] = 0
        return data 
Example 8
Project: darkc0de-old-stuff   Author: tuwid   File: tools.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def nice(level):
            pass 
Example 9
Project: darkc0de-old-stuff   Author: tuwid   File: tools.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def beNice(very_nice=False):
        if very_nice:
            value = 10
        else:
            value = 5
        nice(value) 
Example 10
Project: hostapd-mana   Author: adde88   File: forkedfunc.py    (license) View Source Project 5 votes vote down vote up
def _child(self, nice_level, child_on_start, child_on_exit):
        # right now we need to call a function, but first we need to
        # map all IO that might happen
        sys.stdout = stdout = get_unbuffered_io(1, self.STDOUT)
        sys.stderr = stderr = get_unbuffered_io(2, self.STDERR)
        retvalf = self.RETVAL.open("wb")
        EXITSTATUS = 0
        try:
            if nice_level:
                os.nice(nice_level)
            try:
                if child_on_start is not None:
                    child_on_start()
                retval = self.fun(*self.args, **self.kwargs)
                retvalf.write(marshal.dumps(retval))
                if child_on_exit is not None:
                    child_on_exit()
            except:
                excinfo = py.code.ExceptionInfo()
                stderr.write(str(excinfo._getreprcrash()))
                EXITSTATUS = self.EXITSTATUS_EXCEPTION
        finally:
            stdout.close()
            stderr.close()
            retvalf.close()
        os.close(1)
        os.close(2)
        os._exit(EXITSTATUS) 
Example 11
Project: execnet   Author: pytest-dev   File: test_xspec.py    (license) View Source Project 5 votes vote down vote up
def test_popen_nice(self, makegateway):
        gw = makegateway("popen")

        def getnice(channel):
            import os
            if hasattr(os, 'nice'):
                channel.send(os.nice(0))
            else:
                channel.send(None)
        remotenice = gw.remote_exec(getnice).receive()
        gw.exit()
        if remotenice is not None:
            gw = makegateway("popen//nice=5")
            remotenice2 = gw.remote_exec(getnice).receive()
            assert remotenice2 == remotenice + 5 
Example 12
Project: sslstrip-hsts-openwrt   Author: adde88   File: forkedfunc.py    (license) View Source Project 5 votes vote down vote up
def _child(self, nice_level, child_on_start, child_on_exit):
        # right now we need to call a function, but first we need to
        # map all IO that might happen
        sys.stdout = stdout = get_unbuffered_io(1, self.STDOUT)
        sys.stderr = stderr = get_unbuffered_io(2, self.STDERR)
        retvalf = self.RETVAL.open("wb")
        EXITSTATUS = 0
        try:
            if nice_level:
                os.nice(nice_level)
            try:
                if child_on_start is not None:
                    child_on_start()
                retval = self.fun(*self.args, **self.kwargs)
                retvalf.write(marshal.dumps(retval))
                if child_on_exit is not None:
                    child_on_exit()
            except:
                excinfo = py.code.ExceptionInfo()
                stderr.write(str(excinfo._getreprcrash()))
                EXITSTATUS = self.EXITSTATUS_EXCEPTION
        finally:
            stdout.close()
            stderr.close()
            retvalf.close()
        os.close(1)
        os.close(2)
        os._exit(EXITSTATUS) 
Example 13
Project: Nanopore-read-processor   Author: rrwick   File: process_reads.py    (license) View Source Project 5 votes vote down vote up
def gzip_fast5s(self):
        tarball = self.get_tarball_path()
        if os.path.isfile(tarball):
            os.remove(tarball)

        print('\ngzipping reads into a tar.gz file...', flush=True)

        base_dir = self.base_dir
        if not base_dir.endswith('/'):
            base_dir += '/'

        for directory in self.all_dirs:
            assert directory.startswith(self.base_dir)

        rel_dirs = [x[len(base_dir):] for x in self.all_dirs]

        current_dir = os.getcwd()
        os.chdir(self.base_dir)

        # Use pigz if available to speed up the compression.
        pigz_path = shutil.which('pigz')
        if pigz_path:
            tar_cmd = 'tar cf - ' + ' '.join(rel_dirs) + ' | pigz -9 -p 8 > ' + tarball
        else:
            tar_cmd = 'tar -czvf ' + tarball + ' '.join(rel_dirs)

        tar = subprocess.Popen(tar_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                               preexec_fn=lambda: os.nice(20), shell=True)
        _, _ = tar.communicate()
        tar.wait()
        os.chdir(current_dir) 
Example 14
Project: Nanopore-read-processor   Author: rrwick   File: process_reads.py    (license) View Source Project 5 votes vote down vote up
def tarball_count_is_correct(self):
        tarball = self.get_tarball_path()
        print('Checking that fast5 file count matches that in ' + os.path.basename(tarball) +
              '...  ', end='')
        fast5_count = len(self.all_fast5_files)
        tar_count_cmd = 'pigz -dc ' + tarball + ' | tar tf - | grep -P ".fast5$" | wc -l'
        p = subprocess.Popen(tar_count_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             preexec_fn=lambda: os.nice(20), shell=True)
        out, _ = p.communicate()
        tar_count = int(out.decode())
        match = tar_count == fast5_count
        if match:
            print('all good!')
        return match 
Example 15
Project: Nanopore-read-processor   Author: rrwick   File: process_reads.py    (license) View Source Project 5 votes vote down vote up
def nanonetcall(directory, threads):
    temp_fastq = 'temp_' + str(random.randint(0, 100000000)) + '.fastq'
    nanonetcall_cmd = ['nanonetcall', '--fastq', '--write_events', '--jobs', str(threads),
                       '--max_len', '100000', directory]
    with open(temp_fastq, 'wb') as fastq_out:
        p = subprocess.Popen(nanonetcall_cmd, stdout=fastq_out, stderr=subprocess.PIPE,
                             preexec_fn=lambda: os.nice(20))
        _, _ = p.communicate()
        p.wait()
    remove_if_exists(temp_fastq) 
Example 16
Project: Nanopore-read-processor   Author: rrwick   File: process_reads.py    (license) View Source Project 5 votes vote down vote up
def nanonetcall_2d(directory, threads):
    temp_prefix = 'temp_' + str(random.randint(0, 100000000))
    nanonet2d_cmd = ['nanonet2d', '--fastq', '--write_events', '--jobs', str(threads),
                     '--max_len', '100000', directory, temp_prefix]
    p = subprocess.Popen(nanonet2d_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                         preexec_fn=lambda: os.nice(20))
    _, _ = p.communicate()
    p.wait()
    remove_if_exists(temp_prefix + '_template.fastq')
    remove_if_exists(temp_prefix + '_complement.fastq')
    remove_if_exists(temp_prefix + '_2d.fastq') 
Example 17
Project: godot-python   Author: touilleMan   File: forkedfunc.py    (license) View Source Project 5 votes vote down vote up
def _child(self, nice_level, child_on_start, child_on_exit):
        # right now we need to call a function, but first we need to
        # map all IO that might happen
        sys.stdout = stdout = get_unbuffered_io(1, self.STDOUT)
        sys.stderr = stderr = get_unbuffered_io(2, self.STDERR)
        retvalf = self.RETVAL.open("wb")
        EXITSTATUS = 0
        try:
            if nice_level:
                os.nice(nice_level)
            try:
                if child_on_start is not None:
                    child_on_start()
                retval = self.fun(*self.args, **self.kwargs)
                retvalf.write(marshal.dumps(retval))
                if child_on_exit is not None:
                    child_on_exit()
            except:
                excinfo = py.code.ExceptionInfo()
                stderr.write(str(excinfo._getreprcrash()))
                EXITSTATUS = self.EXITSTATUS_EXCEPTION
        finally:
            stdout.close()
            stderr.close()
            retvalf.close()
        os.close(1)
        os.close(2)
        os._exit(EXITSTATUS) 
Example 18
Project: godot-python   Author: touilleMan   File: forkedfunc.py    (license) View Source Project 5 votes vote down vote up
def _child(self, nice_level, child_on_start, child_on_exit):
        # right now we need to call a function, but first we need to
        # map all IO that might happen
        sys.stdout = stdout = get_unbuffered_io(1, self.STDOUT)
        sys.stderr = stderr = get_unbuffered_io(2, self.STDERR)
        retvalf = self.RETVAL.open("wb")
        EXITSTATUS = 0
        try:
            if nice_level:
                os.nice(nice_level)
            try:
                if child_on_start is not None:
                    child_on_start()
                retval = self.fun(*self.args, **self.kwargs)
                retvalf.write(marshal.dumps(retval))
                if child_on_exit is not None:
                    child_on_exit()
            except:
                excinfo = py.code.ExceptionInfo()
                stderr.write(str(excinfo._getreprcrash()))
                EXITSTATUS = self.EXITSTATUS_EXCEPTION
        finally:
            stdout.close()
            stderr.close()
            retvalf.close()
        os.close(1)
        os.close(2)
        os._exit(EXITSTATUS) 
Example 19
Project: Mac-Python-3.X   Author: L1nwatch   File: learn_os.py    (license) View Source Project 5 votes vote down vote up
def main():
    print(os.nice(0))  # get relative process priority
    print(os.nice(1))  # change relative priority
    print(os.times())  # process times: system, user etc...
    print(os.isatty(0))  # is the file descriptor arg a tty?(0 = stdin)
    print(os.isatty(4))  # 4 is just an arbitrary test value
    print(os.getloadavg())  # UNIX only - number of processes in queue
    print(os.cpu_count())  # New in Python 3.4 
Example 20
Project: dancedeets-monorepo   Author: mikelambert   File: processing.py    (license) View Source Project 5 votes vote down vote up
def _partition_init_worker():
    import signal
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    import os
    os.nice(5) 
Example 21
Project: dancedeets-monorepo   Author: mikelambert   File: old_eval_auto_classifier.py    (license) View Source Project 5 votes vote down vote up
def init_worker():
    import signal
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    import os
    os.nice(5) 
Example 22
Project: GSM-scanner   Author: yosriayed   File: forkedfunc.py    (license) View Source Project 5 votes vote down vote up
def _child(self, nice_level, child_on_start, child_on_exit):
        # right now we need to call a function, but first we need to
        # map all IO that might happen
        sys.stdout = stdout = get_unbuffered_io(1, self.STDOUT)
        sys.stderr = stderr = get_unbuffered_io(2, self.STDERR)
        retvalf = self.RETVAL.open("wb")
        EXITSTATUS = 0
        try:
            if nice_level:
                os.nice(nice_level)
            try:
                if child_on_start is not None:
                    child_on_start()
                retval = self.fun(*self.args, **self.kwargs)
                retvalf.write(marshal.dumps(retval))
                if child_on_exit is not None:
                    child_on_exit()
            except:
                excinfo = py.code.ExceptionInfo()
                stderr.write(str(excinfo._getreprcrash()))
                EXITSTATUS = self.EXITSTATUS_EXCEPTION
        finally:
            stdout.close()
            stderr.close()
            retvalf.close()
        os.close(1)
        os.close(2)
        os._exit(EXITSTATUS) 
Example 23
Project: GSM-scanner   Author: yosriayed   File: forkedfunc.py    (license) View Source Project 5 votes vote down vote up
def _child(self, nice_level, child_on_start, child_on_exit):
        # right now we need to call a function, but first we need to
        # map all IO that might happen
        sys.stdout = stdout = get_unbuffered_io(1, self.STDOUT)
        sys.stderr = stderr = get_unbuffered_io(2, self.STDERR)
        retvalf = self.RETVAL.open("wb")
        EXITSTATUS = 0
        try:
            if nice_level:
                os.nice(nice_level)
            try:
                if child_on_start is not None:
                    child_on_start()
                retval = self.fun(*self.args, **self.kwargs)
                retvalf.write(marshal.dumps(retval))
                if child_on_exit is not None:
                    child_on_exit()
            except:
                excinfo = py.code.ExceptionInfo()
                stderr.write(str(excinfo._getreprcrash()))
                EXITSTATUS = self.EXITSTATUS_EXCEPTION
        finally:
            stdout.close()
            stderr.close()
            retvalf.close()
        os.close(1)
        os.close(2)
        os._exit(EXITSTATUS) 
Example 24
Project: py   Author: pytest-dev   File: forkedfunc.py    (license) View Source Project 5 votes vote down vote up
def _child(self, nice_level, child_on_start, child_on_exit):
        # right now we need to call a function, but first we need to
        # map all IO that might happen
        sys.stdout = stdout = get_unbuffered_io(1, self.STDOUT)
        sys.stderr = stderr = get_unbuffered_io(2, self.STDERR)
        retvalf = self.RETVAL.open("wb")
        EXITSTATUS = 0
        try:
            if nice_level:
                os.nice(nice_level)
            try:
                if child_on_start is not None:
                    child_on_start()
                retval = self.fun(*self.args, **self.kwargs)
                retvalf.write(marshal.dumps(retval))
                if child_on_exit is not None:
                    child_on_exit()
            except:
                excinfo = py.code.ExceptionInfo()
                stderr.write(str(excinfo._getreprcrash()))
                EXITSTATUS = self.EXITSTATUS_EXCEPTION
        finally:
            stdout.close()
            stderr.close()
            retvalf.close()
        os.close(1)
        os.close(2)
        os._exit(EXITSTATUS) 
Example 25
Project: xpybuild   Author: xpybuild   File: platformutils.py    (license) View Source Project 5 votes vote down vote up
def lowerCurrentProcessPriority():
	if buildcommon.isWindows():
		import win32process, win32api,win32con
		win32process.SetPriorityClass(win32api.GetCurrentProcess(), win32process.BELOW_NORMAL_PRIORITY_CLASS)
	else:
		# on unix, people may run nice before executing the process, so 
		# only change the priority unilaterally if it's currently at its 
		# default value
		if os.nice(0) == 0:
			os.nice(1) # change to 1 below the current level 
Example 26
Project: anglerfish   Author: juancarlospaco   File: set_process_priority.py    (license) View Source Project 5 votes vote down vote up
def set_process_priority(nice: bool=True, ionice: bool=False,
                         cpulimit: int=0) -> bool:
    """Set process name and cpu priority."""
    w = " may delay I/O Operations, not recommended on user-facing GUI!."
    try:
        if nice:
            _old = os.getpriority(os.PRIO_PROCESS, 0)
            os.nice(19)  # smooth cpu priority
            log.debug(f"Process CPUs Priority set: from {_old} to 19.")
        elif ionice and which("ionice"):
            log.warning("ionice" + w)
            cmnd = f"{which('ionice')} --ignore --class 3 --pid {os.getpid()}"
            call(cmnd, shell=True)  # I/O nice,should work on Linux and Os X
            log.debug(f"Process PID {os.getpid()} I/O Priority set to: {cmnd}")
        elif cpulimit and which("cpulimit"):
            log.warning("cpulimit" + w)
            log.debug("Launching 1 background 'cpulimit' child subprocess...")
            cpulimit = int(cpulimit if cpulimit > 4 else 5)  # makes 5 the min.
            command = "{0} --include-children --pid={1} --limit={2}".format(
                which("cpulimit"), os.getpid(), cpulimit)
            proces = Popen(command, shell=True)  # This launch a subprocess.
            atexit.register(proces.kill)  # Force Kill subprocess at exit.
            log.debug(f"Process CPUs Max Limits capped to: {command}.")
    except Exception as error:
        log.warning(error)
        return False  # this may fail on windows and its normal, so be silent.
    else:
        return True