Python os.devnull() Examples

The following are code examples for showing how to use os.devnull(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: notify.py    MIT License 7 votes vote down vote up
def convert_image(inpath, outpath, size):
    """Convert an image file using ``sips``.

    Args:
        inpath (str): Path of source file.
        outpath (str): Path to destination file.
        size (int): Width and height of destination image in pixels.

    Raises:
        RuntimeError: Raised if ``sips`` exits with non-zero status.
    """
    cmd = [
        b'sips',
        b'-z', str(size), str(size),
        inpath,
        b'--out', outpath]
    # log().debug(cmd)
    with open(os.devnull, 'w') as pipe:
        retcode = subprocess.call(cmd, stdout=pipe, stderr=subprocess.STDOUT)

    if retcode != 0:
        raise RuntimeError('sips exited with %d' % retcode) 
Example 2
Project: optics   Author: radiasoft   File: uti_plot_matplotlib.py    Apache License 2.0 7 votes vote down vote up
def _running_in_x11(self):
        'Is X11 running?'
        d = os.environ.get('DISPLAY')
        if d is None or d == '':
            return False
        devnull = open(os.devnull, 'wb')
        tries = [
            # xset is not in core install on some OSes
            ['xset', '-q'],
            # This takes a couple of seconds
            ['xterm', '/bin/true']]
        for t in tries:
            try:
                subprocess.call(t, stdout=devnull, stderr=devnull)
                return True
            except:
                pass
        return false 
Example 3
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: distro.py    MIT License 6 votes vote down vote up
def _lsb_release_info(self):
        """
        Get the information items from the lsb_release command output.

        Returns:
            A dictionary containing all information items.
        """
        if not self.include_lsb:
            return {}
        with open(os.devnull, 'w') as devnull:
            try:
                cmd = ('lsb_release', '-a')
                stdout = subprocess.check_output(cmd, stderr=devnull)
            except OSError:  # Command not found
                return {}
        content = stdout.decode(sys.getfilesystemencoding()).splitlines()
        return self._parse_lsb_release_content(content) 
Example 4
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test_utils.py    Apache License 2.0 6 votes vote down vote up
def discard_stderr():
    """
    Discards error output of a routine if invoked as:

    with discard_stderr():
        ...
    """
    with open(os.devnull, 'w') as bit_bucket:
        try:
            stderr_fileno = sys.stderr.fileno()
            old_stderr = os.dup(stderr_fileno)
            try:
                os.dup2(bit_bucket.fileno(), stderr_fileno)
                yield
            finally:
                os.dup2(old_stderr, stderr_fileno)
        except AttributeError:
            # On some systems is stderr not a file descriptor but actually a virtual pipeline
            # that can not be copied
            yield 
Example 5
Project: alfred-urban-dictionary   Author: xilopaint   File: notify.py    MIT License 6 votes vote down vote up
def convert_image(inpath, outpath, size):
    """Convert an image file using ``sips``.

    Args:
        inpath (str): Path of source file.
        outpath (str): Path to destination file.
        size (int): Width and height of destination image in pixels.

    Raises:
        RuntimeError: Raised if ``sips`` exits with non-zero status.
    """
    cmd = [
        b'sips',
        b'-z', str(size), str(size),
        inpath,
        b'--out', outpath]
    # log().debug(cmd)
    with open(os.devnull, 'w') as pipe:
        retcode = subprocess.call(cmd, stdout=pipe, stderr=subprocess.STDOUT)

    if retcode != 0:
        raise RuntimeError('sips exited with %d' % retcode) 
Example 6
Project: advent-of-code-2018   Author: badouralix   File: rust.py    MIT License 6 votes vote down vote up
def __init__(self, file):
        DEVNULL = open(os.devnull, 'wb')
        SubmissionWrapper.__init__(self)
        tmpdir = tempfile.TemporaryDirectory(prefix="aoc")
        tmpdir.cleanup()
        try:
            subprocess.check_output(
                ["cargo", "test", "--bin", file.replace('/', '-')[:-3]], stderr=DEVNULL).decode()
        except subprocess.CalledProcessError as e:
            raise CompilationError(e.output)

        e = subprocess.Popen(["cargo", "build", "--release", "--bin",
                              file.replace('/', '-')[:-3]],
                             env={**os.environ, "CARGO_TARGET_DIR": tmpdir.name},
                             stdout=DEVNULL,
                             stderr=DEVNULL).wait()
        if e > 0:
            raise CompilationError("Could not compile " + file)
        self.executable = tmpdir.name + "/release/" + file.replace('/', '-')[:-3] 
Example 7
Project: epr   Author: wustho   File: epr.py    MIT License 6 votes vote down vote up
def loadstate():
    global STATE, STATEFILE
    if os.getenv("HOME") is not None:
        STATEFILE = os.path.join(os.getenv("HOME"), ".epr")
        if os.path.isdir(os.path.join(os.getenv("HOME"), ".config")):
            configdir = os.path.join(os.getenv("HOME"), ".config", "epr")
            os.makedirs(configdir, exist_ok=True)
            if os.path.isfile(STATEFILE):
                if os.path.isfile(os.path.join(configdir, "config")):
                    os.remove(os.path.join(configdir, "config"))
                shutil.move(STATEFILE, os.path.join(configdir, "config"))
            STATEFILE = os.path.join(configdir, "config")
    elif os.getenv("USERPROFILE") is not None:
        STATEFILE = os.path.join(os.getenv("USERPROFILE"), ".epr")
    else:
        STATEFILE = os.devnull

    if os.path.exists(STATEFILE):
        with open(STATEFILE, "r") as f:
            STATE = json.load(f) 
Example 8
Project: mx   Author: graalvm   File: mx.py    GNU General Public License v2.0 6 votes vote down vote up
def needsBuild(self, newestInput):
        logv('Checking whether to build {} with GNU Make'.format(self.subject.name))
        cmdline, cwd, env = self._build_run_args()
        cmdline += ['-q']

        if _opts.verbose:
            # default out/err stream
            ret_code = run(cmdline, cwd=cwd, env=env, nonZeroIsFatal=False)
        else:
            with open(os.devnull, 'w') as fnull:
                # suppress out/err (redirect to null device)
                ret_code = run(cmdline, cwd=cwd, env=env, nonZeroIsFatal=False, out=fnull, err=fnull)

        if ret_code != 0:
            return (True, "rebuild needed by GNU Make")
        return (False, "up to date according to GNU Make") 
Example 9
Project: mx   Author: graalvm   File: mx.py    GNU General Public License v2.0 6 votes vote down vote up
def verify_library_urls(args):
    """verify that all suite libraries are reachable from at least one of the URLs

    usage: mx verifylibraryurls [--include-mx]
    """
    parser = ArgumentParser(prog='mx verifylibraryurls')
    parser.add_argument('--include-mx', help='', action='store_true', default=primary_suite() == _mx_suite)
    args = parser.parse_args(args)

    ok = True
    _suites = suites(True)
    if args.include_mx:
        _suites.append(_mx_suite)
    for s in _suites:
        for lib in s.libs:
            if (lib.isLibrary() or lib.isResourceLibrary()) and len(lib.get_urls()) != 0 and not download(os.devnull, lib.get_urls(), verifyOnly=True, abortOnError=False, verbose=_opts.verbose):
                ok = False
                log_error('Library {} not available from {}'.format(lib.qualifiedName(), lib.get_urls()))
    if not ok:
        abort('Some libraries are not reachable') 
Example 10
Project: ngo-addons-backport   Author: camptocamp   File: suite.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def run(self, result):
        try:
            subprocess.call(['phantomjs', '-v'],
                            stdout=open(os.devnull, 'w'),
                            stderr=subprocess.STDOUT)
        except OSError:
            test = QUnitTest('phantomjs', 'javascript tests')
            result.startTest(test)
            result.startTest(test)
            result.addSkip(test , "phantomjs command not found")
            result.stopTest(test)
            return

        result._exc_info_to_string = _exc_info_to_string
        try:
            self._run(result)
        finally:
            del result._exc_info_to_string 
Example 11
Project: steamlink   Author: steamlink   File: util.py    MIT License 6 votes vote down vote up
def daemonize() -> None:
	"""Move current process to daemon process."""
	# Create first fork
	pid = os.fork()
	if pid > 0:
		sys.exit(0)

	# Decouple fork
	os.setsid()

	# Create second fork
	pid = os.fork()
	if pid > 0:
		sys.exit(0)

	# redirect standard file descriptors to devnull
	infd = open(os.devnull, 'r')
	outfd = open(os.devnull, 'a+')
	sys.stdout.flush()
	sys.stderr.flush()
	os.dup2(infd.fileno(), sys.stdin.fileno())
	os.dup2(outfd.fileno(), sys.stdout.fileno())
	os.dup2(outfd.fileno(), sys.stderr.fileno()) 
Example 12
Project: EXOSIMS   Author: dsavransky   File: test_Observatory.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setUp(self):

        self.dev_null = open(os.devnull, 'w')

        # self.spec = {"modules": {"PlanetPhysicalModel": "PlanetPhysicalModel"}}
        self.script = resource_path('test-scripts/template_minimal.json')
        with open(self.script) as f:
            self.spec = json.loads(f.read())

        modtype = getattr(EXOSIMS.Prototypes.Observatory.Observatory, '_modtype')
        pkg = EXOSIMS.Observatory
        self.allmods = [get_module(modtype)]
        for loader, module_name, is_pkg in pkgutil.walk_packages(pkg.__path__, pkg.__name__ + '.'):
            if not is_pkg:
                mod = get_module(module_name.split('.')[-1], modtype)
                self.assertTrue(mod._modtype is modtype, '_modtype mismatch for %s' % mod.__name__)
                self.allmods.append(mod) 
Example 13
Project: EXOSIMS   Author: dsavransky   File: test_Completeness.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setUp(self):

        self.dev_null = open(os.devnull, 'w')
        self.script = resource_path('test-scripts/template_minimal.json')
        with open(self.script) as f:
            self.spec = json.loads(f.read())
        
        with RedirectStreams(stdout=self.dev_null):
            self.TL = TargetList(ntargs=10,**copy.deepcopy(self.spec))
        self.TL.dist = np.random.uniform(low=0,high=100,size=self.TL.nStars)*u.pc
        
        modtype = getattr(Completeness,'_modtype')
        pkg = EXOSIMS.Completeness
        self.allmods = [get_module(modtype)]
        for loader, module_name, is_pkg in pkgutil.walk_packages(pkg.__path__, pkg.__name__+'.'):
            if (not 'starkAYO' in module_name) and not is_pkg:
                mod = get_module(module_name.split('.')[-1],modtype)
                self.assertTrue(mod._modtype is modtype,'_modtype mismatch for %s'%mod.__name__)
                self.allmods.append(mod) 
Example 14
Project: EXOSIMS   Author: dsavransky   File: test_PostProcessing.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setUp(self):

        self.dev_null = open(os.devnull, 'w')
        self.specs = {'modules':{'BackgroundSources':' '}}
        script = resource_path('test-scripts/template_minimal.json')
        with open(script) as f:
            spec = json.loads(f.read())
        with RedirectStreams(stdout=self.dev_null):
            self.TL = TargetList(**spec)

        modtype = getattr(EXOSIMS.Prototypes.PostProcessing.PostProcessing,'_modtype')
        pkg = EXOSIMS.PostProcessing
        self.allmods = [get_module(modtype)]
        for loader, module_name, is_pkg in pkgutil.walk_packages(pkg.__path__, pkg.__name__+'.'):
            if not is_pkg:
                mod = get_module(module_name.split('.')[-1],modtype)
                self.assertTrue(mod._modtype is modtype,'_modtype mismatch for %s'%mod.__name__)
                self.allmods.append(mod)


    #Testing some limiting cases below 
Example 15
Project: EXOSIMS   Author: dsavransky   File: test_ZodiacalLight.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setUp(self):
        self.dev_null = open(os.devnull, 'w')
        self.script = resource_path('test-scripts/template_prototype_testing.json')
        with open(self.script) as f:
            self.spec = json.loads(f.read())

        with RedirectStreams(stdout=self.dev_null):
            self.sim = MissionSim.MissionSim(self.script)
        self.TL = self.sim.TargetList
        self.nStars = self.TL.nStars
        self.star_index = np.array(range(0, self.nStars))
        self.Obs = self.sim.Observatory
        self.mode = self.sim.OpticalSystem.observingModes[0]
        self.TK = self.sim.TimeKeeping
        assert self.nStars > 10, "Need at least 10 stars in the target list for the unit test."
        self.unit = 1./u.arcsec**2

        modtype = getattr(EXOSIMS.Prototypes.ZodiacalLight.ZodiacalLight, '_modtype')
        pkg = EXOSIMS.ZodiacalLight
        self.allmods = [get_module(modtype)]
        for loader, module_name, is_pkg in pkgutil.walk_packages(pkg.__path__, pkg.__name__ + '.'):
            if not is_pkg:
                mod = get_module(module_name.split('.')[-1], modtype)
                self.assertTrue(mod._modtype is modtype, '_modtype mismatch for %s' % mod.__name__)
                self.allmods.append(mod) 
Example 16
Project: EXOSIMS   Author: dsavransky   File: test_SimulatedUniverse.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setUp(self):

        self.dev_null = open(os.devnull, 'w')
        self.script = resource_path('test-scripts/template_minimal.json')
        with open(self.script) as f:
            self.spec = json.loads(f.read())
        
        with RedirectStreams(stdout=self.dev_null):
            self.TL = TargetList(ntargs=10,**copy.deepcopy(self.spec))
        self.TL.dist = np.random.uniform(low=0,high=100,size=self.TL.nStars)*u.pc
        
        modtype = getattr(SimulatedUniverse,'_modtype')
        pkg = EXOSIMS.SimulatedUniverse
        self.allmods = [get_module(modtype)]
        for loader, module_name, is_pkg in pkgutil.walk_packages(pkg.__path__, pkg.__name__+'.'):
            if not is_pkg:
                mod = get_module(module_name.split('.')[-1],modtype)
                self.assertTrue(mod._modtype is modtype,'_modtype mismatch for %s'%mod.__name__)
                self.allmods.append(mod) 
Example 17
Project: EXOSIMS   Author: dsavransky   File: test_OpticalSystem.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setUp(self):

        self.dev_null = open(os.devnull, 'w')
        self.script = resource_path('test-scripts/template_minimal.json')
        with open(self.script) as f:
            self.spec = json.loads(f.read())
        
        with RedirectStreams(stdout=self.dev_null):
            self.TL = TargetList(ntargs=10,**copy.deepcopy(self.spec))
        
        modtype = getattr(OpticalSystem,'_modtype')
        pkg = EXOSIMS.OpticalSystem
        self.allmods = [get_module(modtype)]
        for loader, module_name, is_pkg in pkgutil.walk_packages(pkg.__path__, pkg.__name__+'.'):
            if not is_pkg:
                mod = get_module(module_name.split('.')[-1],modtype)
                self.assertTrue(mod._modtype is modtype,'_modtype mismatch for %s'%mod.__name__)
                self.allmods.append(mod) 
Example 18
Project: EXOSIMS   Author: dsavransky   File: test_BackgroundSources.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setUp(self):
        self.dev_null = open(os.devnull, 'w')
        modtype = getattr(EXOSIMS.Prototypes.BackgroundSources.BackgroundSources,'_modtype')
        pkg = EXOSIMS.BackgroundSources
        self.allmods = [get_module(modtype)]
        for loader, module_name, is_pkg in pkgutil.walk_packages(pkg.__path__, pkg.__name__+'.'):
            if not is_pkg:
                mod = get_module(module_name.split('.')[-1],modtype)
                self.assertTrue(mod._modtype is modtype,'_modtype mismatch for %s'%mod.__name__)
                self.allmods.append(mod)
        # need a TargetList object for testing
        script = resource_path('test-scripts/template_prototype_testing.json')
        with open(script) as f:
            spec = json.loads(f.read())
        with RedirectStreams(stdout=self.dev_null):
            self.TL = TargetList(**spec) 
Example 19
Project: service-juniper-vpn   Author: docksal   File: juniper-vpn-wrap.py    GNU General Public License v2.0 6 votes vote down vote up
def tncc_start(self):
        # tncc is the host checker app. It can check different
        # security policies of the host and report back. We have
        # to send it a preauth key (from the DSPREAUTH cookie)
        # and it sends back a new cookie value we submit.
        # After logging in, we send back another cookie to tncc.
        # Subsequently, it contacts https://<vpn_host:443 every
        # 10 minutes.

        if not self.tncc_jar:
            self.tncc_init()

        self.tncc_socket, sock = socket.socketpair(socket.AF_UNIX, socket.SOCK_SEQPACKET)
        null = open(os.devnull, 'w')

        self.tncc_process = subprocess.Popen(['java',
            '-classpath', self.tncc_jar + ':' + self.plugin_jar,
            self.class_name,
            'log_level', '3',
            'postRetries', '6',
            'ivehost', self.vpn_host,
            'home_dir', os.path.expanduser('~'),
            'Parameter0', '',
            'user_agent', self.user_agent,
            ], env={'LD_PRELOAD': self.tncc_preload}, stdin=sock, stdout=null) 
Example 20
Project: sdn-loadbalancer   Author: AnotherKamila   File: testhelpers.py    MIT License 6 votes vote down vote up
def run_cmd(cmd, host=None, background=False):
    if host:
        if subprocess.call(['pgrep', 'p4run'], stdout=open(os.devnull, 'w')) != 0:
            raise RuntimeError('p4run is not running!')
        cmd = ['mx', host] + cmd
    realcmd = [str(a) for a in cmd]
    print(' ****** ', ' '.join(realcmd), ' ****** ')
    if not background:
        return subprocess.call(realcmd)
    else:
        return subprocess.Popen(
            realcmd,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            preexec_fn=os.setsid,
        )

# why is this so difficult 
Example 21
Project: UrsaRobotics_SmartHome   Author: stav98   File: radio.py    GNU General Public License v3.0 5 votes vote down vote up
def play_radio():
    global pid
    with open(os.devnull, 'wb') as nul:
        pid = subprocess.Popen(['mplayer', '-really-quiet', station], stdin=nul,  stdout=subprocess.PIPE)
        #pid = subprocess.Popen(['mplayer','-msglevel',  'all=4',  station], stdin=nul,  stdout=subprocess.PIPE,  stderr=subprocess.STDOUT)

#Αν δεχθεί μήνυμα σε κάποιο topic που έχει κάνει subscribe 
Example 22
Project: clikit   Author: sdispater   File: question.py    MIT License 5 votes vote down vote up
def _has_stty_available(self):
        devnull = open(os.devnull, "w")

        try:
            exit_code = subprocess.call(["stty"], stdout=devnull, stderr=devnull)
        except Exception:
            exit_code = 2

        return exit_code == 0 
Example 23
Project: clikit   Author: sdispater   File: test_question.py    MIT License 5 votes vote down vote up
def has_tty_available():
    devnull = open(os.devnull, "w")
    exit_code = subprocess.call(["stty", "2"], stdout=devnull, stderr=devnull)

    return exit_code == 0 
Example 24
Project: chainer-openai-transformer-lm   Author: soskek   File: utils.py    MIT License 5 votes vote down vote up
def iter_data(
    *datas,
    n_batch=128,
    truncate=False,
    verbose=False,
        max_batches=float("inf")):
    n = len(datas[0])
    if truncate:
        n = (n // n_batch) * n_batch
    n = min(n, max_batches * n_batch)
    n_batches = 0
    if verbose:
        f = sys.stderr
    else:
        f = open(os.devnull, 'w')
    for i in tqdm(
            range(
                0,
                n,
                n_batch),
            total=n //
            n_batch,
            file=f,
            ncols=80,
            leave=False):
        if n_batches >= max_batches:
            raise StopIteration
        if len(datas) == 1:
            yield datas[0][i:i + n_batch]
        else:
            yield (d[i:i + n_batch] for d in datas)
        n_batches += 1 
Example 25
Project: alfred-yubikey-otp   Author: robertoriv   File: notify.py    MIT License 5 votes vote down vote up
def convert_image(inpath, outpath, size):
    """Convert an image file using ``sips``.

    Args:
        inpath (str): Path of source file.
        outpath (str): Path to destination file.
        size (int): Width and height of destination image in pixels.

    Raises:
        RuntimeError: Raised if ``sips`` exits with non-zero status.
    """
    cmd = [
        b'sips',
        b'-z', str(size), str(size),
        inpath,
        b'--out', outpath]
    # log().debug(cmd)
    with open(os.devnull, 'w') as pipe:
        retcode = subprocess.call(cmd, stdout=pipe, stderr=subprocess.STDOUT)

    if retcode != 0:
        raise RuntimeError('sips exited with %d' % retcode) 
Example 26
Project: pyblish-win   Author: pyblish   File: test_stat.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_devices(self):
        if os.path.exists(os.devnull):
            st_mode = self.get_mode(os.devnull, lstat=False)
            self.assertS_IS("CHR", st_mode)
        # Linux block devices, BSD has no block devices anymore
        for blockdev in ("/dev/sda", "/dev/hda"):
            if os.path.exists(blockdev):
                st_mode = self.get_mode(blockdev, lstat=False)
                self.assertS_IS("BLK", st_mode)
                break 
Example 27
Project: pyblish-win   Author: pyblish   File: script_helper.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def python_exit_code(*args):
    cmd_line = [sys.executable, '-E']
    cmd_line.extend(args)
    with open(os.devnull, 'w') as devnull:
        return subprocess.call(cmd_line, stdout=devnull,
                                stderr=subprocess.STDOUT) 
Example 28
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_many_opens(self):
        # Verify that read() and open() promptly close the file descriptor,
        # and don't rely on the garbage collector to free resources.
        self.make_test_archive(TESTFN2)
        with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
            for x in range(100):
                zipf.read('ones')
                with zipf.open('ones') as zopen1:
                    pass
        with open(os.devnull) as f:
            self.assertLess(f.fileno(), 100) 
Example 29
Project: pyblish-win   Author: pyblish   File: test_ensurepip.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_pip_config_file_disabled(self):
        # ensurepip deliberately ignores the pip config file
        # See http://bugs.python.org/issue20053 for details
        ensurepip.bootstrap()
        self.assertEqual(self.os_environ["PIP_CONFIG_FILE"], os.devnull) 
Example 30
Project: pyblish-win   Author: pyblish   File: test_ensurepip.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_pip_config_file_disabled(self):
        # ensurepip deliberately ignores the pip config file
        # See http://bugs.python.org/issue20053 for details
        with fake_pip():
            ensurepip._uninstall_helper()
        self.assertEqual(self.os_environ["PIP_CONFIG_FILE"], os.devnull) 
Example 31
Project: pyblish-win   Author: pyblish   File: test_os.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_devnull(self):
        f = file(os.devnull, 'w')
        f.write('hello')
        f.close()
        f = file(os.devnull, 'r')
        self.assertEqual(f.read(), '')
        f.close() 
Example 32
Project: pyblish-win   Author: pyblish   File: process.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _bootstrap(self):
        from . import util
        global _current_process

        try:
            self._children = set()
            self._counter = itertools.count(1)
            try:
                sys.stdin.close()
                sys.stdin = open(os.devnull)
            except (OSError, ValueError):
                pass
            _current_process = self
            util._finalizer_registry.clear()
            util._run_after_forkers()
            util.info('child process calling self.run()')
            try:
                self.run()
                exitcode = 0
            finally:
                util._exit_function()
        except SystemExit, e:
            if not e.args:
                exitcode = 1
            elif isinstance(e.args[0], int):
                exitcode = e.args[0]
            else:
                sys.stderr.write(str(e.args[0]) + '\n')
                sys.stderr.flush()
                exitcode = 1 
Example 33
Project: InkscapeBarrelDistortion   Author: ucuapps   File: distortion.py    MIT License 5 votes vote down vote up
def __init__(self):
        inkex.Effect.__init__(self)
        try:
            self.tty = open("/dev/tty", 'w')
        except:
            self.tty = open(os.devnull, 'w')
        self.OptionParser.add_option("-l",
                                     "--lambda",
                                     action="store",
                                     type="float",
                                     dest="lambda_coef",
                                     default=-5.0,
                                     help="command line help") 
Example 34
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: index.py    MIT License 5 votes vote down vote up
def __init__(self, url=None):
        """
        Initialise an instance.

        :param url: The URL of the index. If not specified, the URL for PyPI is
                    used.
        """
        self.url = url or DEFAULT_INDEX
        self.read_configuration()
        scheme, netloc, path, params, query, frag = urlparse(self.url)
        if params or query or frag or scheme not in ('http', 'https'):
            raise DistlibException('invalid repository: %s' % self.url)
        self.password_handler = None
        self.ssl_verifier = None
        self.gpg = None
        self.gpg_home = None
        with open(os.devnull, 'w') as sink:
            # Use gpg by default rather than gpg2, as gpg2 insists on
            # prompting for passwords
            for s in ('gpg', 'gpg2'):
                try:
                    rc = subprocess.check_call([s, '--version'], stdout=sink,
                                               stderr=sink)
                    if rc == 0:
                        self.gpg = s
                        break
                except OSError:
                    pass 
Example 35
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: configuration.py    MIT License 5 votes vote down vote up
def _load_config_files(self):
        # type: () -> None
        """Loads configuration from configuration files
        """
        config_files = dict(self._iter_config_files())
        if config_files[kinds.ENV][0:1] == [os.devnull]:
            logger.debug(
                "Skipping loading configuration files due to "
                "environment's PIP_CONFIG_FILE being os.devnull"
            )
            return

        for variant, files in config_files.items():
            for fname in files:
                # If there's specific variant set in `load_only`, load only
                # that variant, not the others.
                if self.load_only is not None and variant != self.load_only:
                    logger.debug(
                        "Skipping file '%s' (variant: %s)", fname, variant
                    )
                    continue

                parser = self._load_file(variant, fname)

                # Keeping track of the parsers used
                self._parsers[variant].append((fname, parser)) 
Example 36
Project: flasky   Author: RoseOu   File: index.py    MIT License 5 votes vote down vote up
def __init__(self, url=None):
        """
        Initialise an instance.

        :param url: The URL of the index. If not specified, the URL for PyPI is
                    used.
        """
        self.url = url or DEFAULT_INDEX
        self.read_configuration()
        scheme, netloc, path, params, query, frag = urlparse(self.url)
        if params or query or frag or scheme not in ('http', 'https'):
            raise DistlibException('invalid repository: %s' % self.url)
        self.password_handler = None
        self.ssl_verifier = None
        self.gpg = None
        self.gpg_home = None
        with open(os.devnull, 'w') as sink:
            for s in ('gpg2', 'gpg'):
                try:
                    rc = subprocess.check_call([s, '--version'], stdout=sink,
                                               stderr=sink)
                    if rc == 0:
                        self.gpg = s
                        break
                except OSError:
                    pass 
Example 37
Project: flasky   Author: RoseOu   File: baseparser.py    MIT License 5 votes vote down vote up
def get_config_files(self):
        config_file = os.environ.get('PIP_CONFIG_FILE', False)
        if config_file == os.devnull:
            return []
        if config_file and os.path.exists(config_file):
            return [config_file]
        return [default_config_file] 
Example 38
Project: flasky   Author: RoseOu   File: firefox_binary.py    MIT License 5 votes vote down vote up
def __init__(self, firefox_path=None, log_file=None):
        """
        Creates a new instance of Firefox binary.

        :Args:
         - firefox_path - Path to the Firefox executable. By default, it will be detected from the standard locations.
         - log_file - A file object to redirect the firefox process output to. It can be sys.stdout.
                      Please note that with parallel run the output won't be synchronous.
                      By default, it will be redirected to /dev/null.
        """
        self._start_cmd = firefox_path
        # We used to default to subprocess.PIPE instead of /dev/null, but after
        # a while the pipe would fill up and Firefox would freeze.
        self._log_file = log_file or open(os.devnull, "wb")
        self.command_line = None
        if self._start_cmd is None:
            self._start_cmd = self._get_firefox_start_cmd()
        if not self._start_cmd.strip():
          raise Exception("Failed to find firefox binary. You can set it by specifying the path to 'firefox_binary':\n\nfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinary\n\n" +
            "binary = FirefoxBinary('/path/to/binary')\ndriver = webdriver.Firefox(firefox_binary=binary)")
        # Rather than modifying the environment of the calling Python process
        # copy it and modify as needed.
        self._firefox_env = os.environ.copy()
        self._firefox_env["MOZ_CRASHREPORTER_DISABLE"] = "1"
        self._firefox_env["MOZ_NO_REMOTE"] = "1"
        self._firefox_env["NO_EM_RESTART"] = "1" 
Example 39
Project: flasky   Author: RoseOu   File: service.py    MIT License 5 votes vote down vote up
def start(self):
        """
        Starts the SafariDriver Service.

        :Exceptions:
         - WebDriverException : Raised either when it can't start the service
           or when it can't connect to the service
        """
        kwargs = dict()
        if self.quiet:
            devnull_out = open(devnull, 'w')
            kwargs.update(stdout=devnull_out,
                          stderr=devnull_out)
        try:
            self.process = subprocess.Popen(["java", "-jar", self.path, "-port", "%s" % self.port],
                                            **kwargs)
        except:
            raise WebDriverException(
                "SafariDriver executable needs to be available in the path.")
        time.sleep(10)
        count = 0
        while not utils.is_connectable(self.port):
            count += 1
            time.sleep(1)
            if count == 30:
                 raise WebDriverException("Can not connect to the SafariDriver") 
Example 40
Project: flasky   Author: RoseOu   File: test_sandbox.py    MIT License 5 votes vote down vote up
def test_devnull(self):
        if sys.version < '2.4':
            return
        sandbox = DirectorySandbox(self.dir)
        sandbox.run(self._file_writer(os.devnull)) 
Example 41
Project: dauber   Author: OpenDataAnalytics   File: playbook.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, playbook, inventory=None, env=None, extra_vars=None,
                 tags=None, verbosity=None, logger=None,
                 ansible_playbook_bin="ansible-playbook"):

        self.playbook = playbook

        if logger is None:
            self.logger = logging.getLogger(self.__class__.__name__)
            if not len(self.logger.handlers):
                formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
                ch = logging.StreamHandler()
                ch.setFormatter(formatter)
                self.logger.addHandler(ch)
        else:
            self.logger = logger

        self.inventory = inventory

        self._env = os.environ.copy()
        self._env.update(env if env is not None else {})

        self._extra_vars = [extra_vars] if extra_vars else []

        self.tags = tags if tags is not None else []
        self.verbosity = verbosity if verbosity is not None else 1

        self.ansible_playbook_bin = ansible_playbook_bin

        with open(os.devnull, 'w') as fnull:
            if subprocess.call(["which", self.ansible_playbook_bin],
                               stdout=fnull, stderr=fnull) != 0:
                self.logger.error("Could not locate '{}' script"
                                  .format(self.ansible_playbook_bin))

        self._inventory_path = None 
Example 42
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: novalib.py    Apache License 2.0 5 votes vote down vote up
def execute_get_output(*command):
    """Execute and return stdout."""
    devnull = open(os.devnull, 'w')
    command = map(str, command)
    proc = subprocess.Popen(command, close_fds=True,
                            stdout=subprocess.PIPE, stderr=devnull)
    devnull.close()
    stdout = proc.communicate()[0]
    return stdout.strip() 
Example 43
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: novalib.py    Apache License 2.0 5 votes vote down vote up
def execute(*command):
    """Execute without returning stdout."""
    devnull = open(os.devnull, 'w')
    command = map(str, command)
    subprocess.call(command, close_fds=True, stdout=devnull, stderr=devnull)
    devnull.close() 
Example 44
Project: sic   Author: Yanixos   File: index.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, url=None):
        """
        Initialise an instance.

        :param url: The URL of the index. If not specified, the URL for PyPI is
                    used.
        """
        self.url = url or DEFAULT_INDEX
        self.read_configuration()
        scheme, netloc, path, params, query, frag = urlparse(self.url)
        if params or query or frag or scheme not in ('http', 'https'):
            raise DistlibException('invalid repository: %s' % self.url)
        self.password_handler = None
        self.ssl_verifier = None
        self.gpg = None
        self.gpg_home = None
        self.rpc_proxy = None
        with open(os.devnull, 'w') as sink:
            # Use gpg by default rather than gpg2, as gpg2 insists on
            # prompting for passwords
            for s in ('gpg', 'gpg2'):
                try:
                    rc = subprocess.check_call([s, '--version'], stdout=sink,
                                               stderr=sink)
                    if rc == 0:
                        self.gpg = s
                        break
                except OSError:
                    pass 
Example 45
Project: sic   Author: Yanixos   File: baseparser.py    GNU General Public License v3.0 5 votes vote down vote up
def get_config_files(self):
        # the files returned by this method will be parsed in order with the
        # first files listed being overridden by later files in standard
        # ConfigParser fashion
        config_file = os.environ.get('PIP_CONFIG_FILE', False)
        if config_file == os.devnull:
            return []

        # at the base we have any site-wide configuration
        files = list(site_config_files)

        # per-user configuration next
        if not self.isolated:
            if config_file and os.path.exists(config_file):
                files.append(config_file)
            else:
                # This is the legacy config file, we consider it to be a lower
                # priority than the new file location.
                files.append(legacy_config_file)

                # This is the new config file, we consider it to be a higher
                # priority than the legacy file.
                files.append(
                    os.path.join(
                        appdirs.user_config_dir("pip"),
                        config_basename,
                    )
                )

        # finally virtualenv configuration first trumping others
        if running_under_virtualenv():
            venv_config_file = os.path.join(
                sys.prefix,
                config_basename,
            )
            if os.path.exists(venv_config_file):
                files.append(venv_config_file)

        return files 
Example 46
Project: face_rekognition   Author: cnidus   File: EpsImagePlugin.py    GNU General Public License v3.0 5 votes vote down vote up
def has_ghostscript():
    if gs_windows_binary:
        return True
    if not sys.platform.startswith('win'):
        import subprocess
        try:
            with open(os.devnull, 'wb') as devnull:
                subprocess.check_call(['gs', '--version'], stdout=devnull)
            return True
        except OSError:
            # no ghostscript
            pass
    return False 
Example 47
Project: AshsSDK   Author: thehappydinoa   File: index.py    MIT License 5 votes vote down vote up
def __init__(self, url=None):
        """
        Initialise an instance.

        :param url: The URL of the index. If not specified, the URL for PyPI is
                    used.
        """
        self.url = url or DEFAULT_INDEX
        self.read_configuration()
        scheme, netloc, path, params, query, frag = urlparse(self.url)
        if params or query or frag or scheme not in ('http', 'https'):
            raise DistlibException('invalid repository: %s' % self.url)
        self.password_handler = None
        self.ssl_verifier = None
        self.gpg = None
        self.gpg_home = None
        self.rpc_proxy = None
        with open(os.devnull, 'w') as sink:
            # Use gpg by default rather than gpg2, as gpg2 insists on
            # prompting for passwords
            for s in ('gpg', 'gpg2'):
                try:
                    rc = subprocess.check_call([s, '--version'], stdout=sink,
                                               stderr=sink)
                    if rc == 0:
                        self.gpg = s
                        break
                except OSError:
                    pass 
Example 48
Project: AshsSDK   Author: thehappydinoa   File: baseparser.py    MIT License 5 votes vote down vote up
def get_config_files(self):
        # the files returned by this method will be parsed in order with the
        # first files listed being overridden by later files in standard
        # ConfigParser fashion
        config_file = os.environ.get('PIP_CONFIG_FILE', False)
        if config_file == os.devnull:
            return []

        # at the base we have any site-wide configuration
        files = list(site_config_files)

        # per-user configuration next
        if not self.isolated:
            if config_file and os.path.exists(config_file):
                files.append(config_file)
            else:
                # This is the legacy config file, we consider it to be a lower
                # priority than the new file location.
                files.append(legacy_config_file)

                # This is the new config file, we consider it to be a higher
                # priority than the legacy file.
                files.append(
                    os.path.join(
                        appdirs.user_config_dir("pip"),
                        config_basename,
                    )
                )

        # finally virtualenv configuration first trumping others
        if running_under_virtualenv():
            venv_config_file = os.path.join(
                sys.prefix,
                config_basename,
            )
            if os.path.exists(venv_config_file):
                files.append(venv_config_file)

        return files 
Example 49
Project: rgc   Author: TACC   File: __init__.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _retry_call(self, cmd, url, times=3):
		'''
		Retries the check_call command

		# Parameters
		cmd (str): Command to run
		url (str): Image url used to pull
		times (int): Number of retries allowed

		# Returns
		bool: Whether the command succeeded or not
		'''
		self.logger.debug("Running: "+cmd)
		FNULL = open(os.devnull, 'w')
		for i in range(times):
			try:
				sp.check_call(cmd, shell=True, stdout=FNULL, stderr=FNULL)
			except KeyboardInterrupt as e:
				FNULL.close()
				sys.exit()
			except sp.CalledProcessError:
				if i < times-1:
					self.logger.debug("Attempting to pull %s again"%(url))
					sleep(2)
					continue
				else:
					FNULL.close()
					return False
			break
		return True
		FNULL.close() 
Example 50
Project: optics   Author: radiasoft   File: uti_plot_matplotlib.py    Apache License 2.0 5 votes vote down vote up
def __enter__(self):
            'Redirects stderr to devnull, saving _prev_stderr'
            if sys.stderr is None or sys.__stderr__ is None:
                return
            sys.stderr.flush()
            fno = sys.__stderr__.fileno() #OC150814
            if(fno >= 0):
                null = os.open(os.devnull, os.O_WRONLY)
                #self._prev_stderr = os.dup(sys.__stderr__.fileno())
                self._prev_stderr = os.dup(fno)
                os.dup2(null, sys.__stderr__.fileno())
                os.close(null) 
Example 51
Project: csvpandas   Author: crosenth   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.funcname = '_'.join(self.id().split('.')[-2:])
        self.suppress_output = log.getEffectiveLevel() >= logging.INFO
        if self.suppress_output:
            sys.stdout = sys.stderr = open(os.devnull, 'w') 
Example 52
Project: presto-admin   Author: prestosql   File: release.py    Apache License 2.0 5 votes vote down vote up
def _send_installer_post_request(self, release_url, installer_name, authorization_string, command_args):
        installer_path = os.path.join(self.directory, 'dist/', installer_name)
        with open(os.devnull, 'w') as dev_null:
            subprocess.check_call(command_args, stdout=dev_null, stderr=dev_null)
        with open(installer_path, mode='rb') as online_installer:
            GithubReleaser._send_bztar_post_request('%s?name=%s' % (release_url, installer_name),
                                                    online_installer,
                                                    authorization_string,
                                                    os.path.getsize(installer_path))
        print 'Successfully posted %s' % installer_name 
Example 53
Project: audio   Author: pytorch   File: generate_test_stft_data.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(exe_path, scp_path, out_dir, wave_len, num_outputs, remove_files, log_level):
    logging.basicConfig(level=log_level)
    for i in range(num_outputs):
        inputs = {
            'blackman_coeff': '%.4f' % (random.random() * 5),
            'dither': '0',
            'energy_floor': '%.4f' % (random.random() * 5),
            'frame_length': '%.4f' % (float(random.randint(2, wave_len - 1)) / 16000 * 1000),
            'frame_shift': '%.4f' % (float(random.randint(1, wave_len - 1)) / 16000 * 1000),
            'preemphasis_coefficient': '%.2f' % random.random(),
            'raw_energy': utils.generate_rand_boolean(),
            'remove_dc_offset': utils.generate_rand_boolean(),
            'round_to_power_of_two': utils.generate_rand_boolean(),
            'snip_edges': utils.generate_rand_boolean(),
            'subtract_mean': utils.generate_rand_boolean(),
            'window_type': utils.generate_rand_window_type()
        }

        fn = 'spec-' + ('-'.join(list(inputs.values())))

        out_fn = out_dir + fn + '.ark'

        arg = [exe_path]
        arg += ['--' + k.replace('_', '-') + '=' + inputs[k] for k in inputs]
        arg += [scp_path, out_fn]

        logging.info(fn)
        logging.info(inputs)
        logging.info(' '.join(arg))

        try:
            if log_level == 'INFO':
                subprocess.call(arg)
            else:
                subprocess.call(arg, stderr=open(os.devnull, 'wb'), stdout=open(os.devnull, 'wb'))
            logging.info('success')
        except Exception:
            if remove_files and os.path.exists(out_fn):
                os.remove(out_fn) 
Example 54
Project: EXOSIMS   Author: dsavransky   File: test_StarCatalog.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):

        self.dev_null = open(os.devnull, 'w')
        
        modtype = getattr(StarCatalog,'_modtype')
        pkg = EXOSIMS.StarCatalog
        self.allmods = [get_module(modtype)]
        for loader, module_name, is_pkg in pkgutil.walk_packages(pkg.__path__, pkg.__name__+'.'):
            if (not 'Gaia' in module_name) and \
            not is_pkg:
                mod = get_module(module_name.split('.')[-1],modtype)
                self.assertTrue(mod._modtype is modtype,'_modtype mismatch for %s'%mod.__name__)
                self.allmods.append(mod) 
Example 55
Project: EXOSIMS   Author: dsavransky   File: test_SurveySimulation.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):

        self.dev_null = open(os.devnull, 'w')
        self.script = resource_path('test-scripts/simplest.json')
        with open(self.script) as f:
            self.spec = json.loads(f.read())
    
        modtype = getattr(SurveySimulation,'_modtype')
        pkg = EXOSIMS.SurveySimulation
        self.allmods = [get_module(modtype)]
        for loader, module_name, is_pkg in pkgutil.walk_packages(pkg.__path__, pkg.__name__+'.'):
            if not is_pkg:
                mod = get_module(module_name.split('.')[-1],modtype)
                self.assertTrue(mod._modtype is modtype,'_modtype mismatch for %s'%mod.__name__)
                self.allmods.append(mod) 
Example 56
Project: EXOSIMS   Author: dsavransky   File: test_DulzPlavchan.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.dev_null = open(os.devnull, 'w')
        self.occDataPath = resource_path('PlanetPopulation/NominalOcc_Mass.csv')
        self.spec = {"modules": {"PlanetPhysicalModel": "PlanetPhysicalModel"},
                     "occDataPath": self.occDataPath} 
Example 57
Project: EXOSIMS   Author: dsavransky   File: test_PlanetPopulation.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):

        self.dev_null = open(os.devnull, 'w')

        self.spec = {"modules":{"PlanetPhysicalModel" : "PlanetPhysicalModel"}}
    
        modtype = getattr(EXOSIMS.Prototypes.PlanetPopulation.PlanetPopulation,'_modtype')
        pkg = EXOSIMS.PlanetPopulation
        self.allmods = [get_module(modtype)]
        for loader, module_name, is_pkg in pkgutil.walk_packages(pkg.__path__, pkg.__name__+'.'):
            if not is_pkg:
                mod = get_module(module_name.split('.')[-1],modtype)
                self.assertTrue(mod._modtype is modtype,'_modtype mismatch for %s'%mod.__name__)
                self.allmods.append(mod) 
Example 58
Project: EXOSIMS   Author: dsavransky   File: test_GarrettCompleteness.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):

        self.dev_null = open(os.devnull, 'w')
        self.script = resource_path('test-scripts/template_minimal.json')
        with open(self.script) as f:
            self.spec = json.loads(f.read())
        self.spec['modules']['PlanetPopulation'] = 'AlbedoByRadius'
        self.spec['prange'] = [0.1,0.5]
        self.spec['Rprange'] = [1,10]
        self.script2 = resource_path('test-scripts/simplest.json')
        with open(self.script2) as f:
            self.spec2 = json.loads(f.read()) 
Example 59
Project: EXOSIMS   Author: dsavransky   File: test_CheckScript.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.dev_null = open(os.devnull,'w')
        # use template_minimal.json
        self.script1path = resource_path('test-scripts/template_minimal.json')
        self.script1dict = json.loads(open(self.script1path).read())
        self.script2path = resource_path('test-scripts/template_prototype_testing.json')
        self.script2dict = json.loads(open(self.script2path).read())
        self.script3path = resource_path('test-scripts/template_completeness_testing.json')
        self.script3dict = json.loads(open(self.script3path).read()) 
Example 60
Project: EXOSIMS   Author: dsavransky   File: test_PlanetPhysicalModel.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):

        self.dev_null = open(os.devnull, 'w')

        modtype = getattr(EXOSIMS.Prototypes.PlanetPhysicalModel.PlanetPhysicalModel,'_modtype')
        pkg = EXOSIMS.PlanetPhysicalModel
        self.allmods = [get_module(modtype)]
        for loader, module_name, is_pkg in pkgutil.walk_packages(pkg.__path__,pkg.__name__+'.'):
            if not is_pkg:
                mod = get_module(module_name.split('.')[-1],modtype)
                self.assertTrue(mod._modtype is modtype,'_modtype mismatch for %s'%mod.__name__)
                self.allmods.append(mod) 
Example 61
Project: EXOSIMS   Author: dsavransky   File: test_TimeKeeping.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        # print '[setup] ',
        # do not instantiate it
        self.fixture = TimeKeeping

        self.dev_null = open(os.devnull, 'w')
        self.script1 = resource_path('test-scripts/simplest.json')
        self.script2 = resource_path('test-scripts/simplest_initOB.json')
    
        modtype = getattr(SurveySimulation,'_modtype')
        self.allmods = [get_module(modtype)] 
Example 62
Project: Scripts   Author: Bilingual-Annotation-Task-Force   File: OOVs.py    MIT License 5 votes vote down vote up
def OOV_remove( tokens, D1, D2=PyDict() ):
    '''Removes OOVs from tokens list based on two dictionaries. PyDictionary module used for Dictionary 2 default.'''

    import string

    if type( D2 ) in { set, list, tuple, dict }:
        def condition3( word, D2 ): #condition for IF statement in FOR loop
            return word not in D2
        
    else: #assume PyDictionary
        
        def condition3( word, D2 ):
            return D2.meaning( word ) == None #This line would print to the console on each OOV if the STDOUT were not changed.

        import sys, os
        orig_stdout = sys.stdout #to save for later
        sys.stdout = open( os.devnull, 'w' ) #prevents printing to console during PyDictionary usage

    t = list( tokens ) #to become output tokens LIST with OOVs removed
    OOVs = {} #to become DICT containing removed OOVs hashed with their original indices in TOKENS
    d = 0 #index offset to account for already removed OOV words

    for i in range( 0, len(tokens) ):
        
        word = tokens[i]
        
        if word not in string.punctuation and word not in D1 and condition3( word, D2 ):
            OOVs.update({ i+1 : word }) #can remove "+1" after "i" on this line if zero-indexing desired.
            del t[i-d]
            d += 1

    if type( D2 ) not in { set, list, tuple, dict }:            
        sys.stdout = orig_stdout #restore stdout
    
    return ( t, OOVs ) 
Example 63
Project: smother   Author: ChrisBeaumont   File: test_plugins.py    MIT License 5 votes vote down vote up
def test_nose_collection():
    with NamedTemporaryFile() as report, open(os.devnull, 'w') as devnull:
        check_call(
            ['nosetests',
             'smother/tests/demo_testsuite.py',
             '--with-smother',
             '--smother-package=smother.tests.demo',
             '--smother-output={}'.format(report.name)
             ],
            stdout=devnull,
            stderr=devnull)

        report.seek(0)
        contents = report.read().decode('utf8')
        assert json.loads(contents) == expected_nose 
Example 64
Project: smother   Author: ChrisBeaumont   File: test_plugins.py    MIT License 5 votes vote down vote up
def test_pytest_collection():
    with NamedTemporaryFile() as report, open(os.devnull, 'w') as devnull:
        check_call(
            ['py.test',
             'smother/tests/demo_testsuite.py',
             '--smother-cover',
             '--smother=smother.tests.demo',
             '--smother-output={}'.format(report.name)
             ],
            stdout=devnull,
            stderr=devnull)

        report.seek(0)
        contents = report.read().decode('utf8')
        assert json.loads(contents) == expected_pytest 
Example 65
Project: pywren-ibm-cloud   Author: pywren   File: utils.py    Apache License 2.0 5 votes vote down vote up
def clean_bucket(bucket, prefix, storage_config, sleep=5, log=False):
    """
    Wrapper of clean_os_bucket(). Use this method only when storage_config is
    in JSON format. In any other case, call directly clean_os_bucket() method.
    """
    from pywren_ibm_cloud.storage import InternalStorage
    internal_storage = InternalStorage(json.loads(storage_config))
    # sys.stdout = open(os.devnull, 'w')
    clean_os_bucket(bucket, prefix, internal_storage, sleep, log)
    # sys.stdout = sys.__stdout__ 
Example 66
Project: shenfun   Author: spectralDNS   File: setup.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def has_flag(compiler, flagname):
    """Return a boolean indicating whether a flag name is supported on
    the specified compiler.
    """
    devnull = open(os.devnull, "w")
    p = subprocess.Popen([compiler.compiler[0], '-E', '-'] + [flagname],
                         stdin=subprocess.PIPE, stdout=devnull, stderr=devnull)
    p.communicate("")
    return True if p.returncode == 0 else False 
Example 67
Project: gnocchi   Author: gnocchixyz   File: test_bin.py    Apache License 2.0 5 votes vote down vote up
def test_gnocchi_config_generator_run(self):
        with open(os.devnull, 'w') as f:
            subp = subprocess.Popen(['gnocchi-config-generator'], stdout=f)
        self.assertEqual(0, subp.wait()) 
Example 68
Project: pyblish-win   Author: pyblish   File: webbrowser.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def _invoke(self, args, remote, autoraise):
        raise_opt = []
        if remote and self.raise_opts:
            # use autoraise argument only for remote invocation
            autoraise = int(autoraise)
            opt = self.raise_opts[autoraise]
            if opt: raise_opt = [opt]

        cmdline = [self.name] + raise_opt + args

        if remote or self.background:
            inout = file(os.devnull, "r+")
        else:
            # for TTY browsers, we need stdin/out
            inout = None
        # if possible, put browser in separate process group, so
        # keyboard interrupts don't affect browser as well as Python
        setsid = getattr(os, 'setsid', None)
        if not setsid:
            setsid = getattr(os, 'setpgrp', None)

        p = subprocess.Popen(cmdline, close_fds=True, stdin=inout,
                             stdout=(self.redirect_stdout and inout or None),
                             stderr=inout, preexec_fn=setsid)
        if remote:
            # wait five seconds. If the subprocess is not finished, the
            # remote invocation has (hopefully) started a new instance.
            time.sleep(1)
            rc = p.poll()
            if rc is None:
                time.sleep(4)
                rc = p.poll()
                if rc is None:
                    return True
            # if remote call failed, open() will try direct invocation
            return not rc
        elif self.background:
            if p.poll() is None:
                return True
            else:
                return False
        else:
            return not p.wait() 
Example 69
Project: pyblish-win   Author: pyblish   File: webbrowser.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def open(self, url, new=0, autoraise=True):
        # XXX Currently I know no way to prevent KFM from opening a new win.
        if new == 2:
            action = "newTab"
        else:
            action = "openURL"

        devnull = file(os.devnull, "r+")
        # if possible, put browser in separate process group, so
        # keyboard interrupts don't affect browser as well as Python
        setsid = getattr(os, 'setsid', None)
        if not setsid:
            setsid = getattr(os, 'setpgrp', None)

        try:
            p = subprocess.Popen(["kfmclient", action, url],
                                 close_fds=True, stdin=devnull,
                                 stdout=devnull, stderr=devnull)
        except OSError:
            # fall through to next variant
            pass
        else:
            p.wait()
            # kfmclient's return code unfortunately has no meaning as it seems
            return True

        try:
            p = subprocess.Popen(["konqueror", "--silent", url],
                                 close_fds=True, stdin=devnull,
                                 stdout=devnull, stderr=devnull,
                                 preexec_fn=setsid)
        except OSError:
            # fall through to next variant
            pass
        else:
            if p.poll() is None:
                # Should be running now.
                return True

        try:
            p = subprocess.Popen(["kfm", "-d", url],
                                 close_fds=True, stdin=devnull,
                                 stdout=devnull, stderr=devnull,
                                 preexec_fn=setsid)
        except OSError:
            return False
        else:
            return (p.poll() is None) 
Example 70
Project: face_rekognition   Author: cnidus   File: IcnsImagePlugin.py    GNU General Public License v3.0 4 votes vote down vote up
def _save(im, fp, filename):
    """
    Saves the image as a series of PNG files,
    that are then converted to a .icns file
    using the macOS command line utility 'iconutil'.

    macOS only.
    """
    if hasattr(fp, "flush"):
        fp.flush()

    # create the temporary set of pngs
    iconset = tempfile.mkdtemp('.iconset')
    last_w = None
    last_im = None
    for w in [16, 32, 128, 256, 512]:
        prefix = 'icon_{}x{}'.format(w, w)

        if last_w == w:
            im_scaled = last_im
        else:
            im_scaled = im.resize((w, w), Image.LANCZOS)
        im_scaled.save(os.path.join(iconset, prefix+'.png'))

        im_scaled = im.resize((w*2, w*2), Image.LANCZOS)
        im_scaled.save(os.path.join(iconset, prefix+'@2x.png'))
        last_im = im_scaled

    # iconutil -c icns -o {} {}
    from subprocess import Popen, PIPE, CalledProcessError

    convert_cmd = ["iconutil", "-c", "icns", "-o", filename, iconset]
    with open(os.devnull, 'wb') as devnull:
        convert_proc = Popen(convert_cmd, stdout=PIPE, stderr=devnull)

    convert_proc.stdout.close()

    retcode = convert_proc.wait()

    # remove the temporary files
    shutil.rmtree(iconset)

    if retcode:
        raise CalledProcessError(retcode, convert_cmd) 
Example 71
Project: face_rekognition   Author: cnidus   File: GifImagePlugin.py    GNU General Public License v3.0 4 votes vote down vote up
def _save_netpbm(im, fp, filename):

    # Unused by default.
    # To use, uncomment the register_save call at the end of the file.
    #
    # If you need real GIF compression and/or RGB quantization, you
    # can use the external NETPBM/PBMPLUS utilities.  See comments
    # below for information on how to enable this.

    import os
    from subprocess import Popen, check_call, PIPE, CalledProcessError
    file = im._dump()

    with open(filename, 'wb') as f:
        if im.mode != "RGB":
            with open(os.devnull, 'wb') as devnull:
                check_call(["ppmtogif", file], stdout=f, stderr=devnull)
        else:
            # Pipe ppmquant output into ppmtogif
            # "ppmquant 256 %s | ppmtogif > %s" % (file, filename)
            quant_cmd = ["ppmquant", "256", file]
            togif_cmd = ["ppmtogif"]
            with open(os.devnull, 'wb') as devnull:
                quant_proc = Popen(quant_cmd, stdout=PIPE, stderr=devnull)
                togif_proc = Popen(togif_cmd, stdin=quant_proc.stdout,
                                   stdout=f, stderr=devnull)

            # Allow ppmquant to receive SIGPIPE if ppmtogif exits
            quant_proc.stdout.close()

            retcode = quant_proc.wait()
            if retcode:
                raise CalledProcessError(retcode, quant_cmd)

            retcode = togif_proc.wait()
            if retcode:
                raise CalledProcessError(retcode, togif_cmd)

    try:
        os.unlink(file)
    except OSError:
        pass


# Force optimization so that we can test performance against
# cases where it took lots of memory and time previously. 
Example 72
Project: fine-lm   Author: akzaidi   File: batch_env_factory.py    MIT License 4 votes vote down vote up
def __init__(self, constructor, xvfb):
    """Step environment in a separate process for lock free parallelism.

    The environment will be created in the external process by calling the
    specified callable. This can be an environment class, or a function
    creating the environment and potentially wrapping it. The returned
    environment should not access global variables.

    Args:
      constructor: Callable that creates and returns an OpenAI gym environment.
      xvfb:  Frame buffer.

    Attributes:
      observation_space: The cached observation space of the environment.
      action_space: The cached action space of the environment.
    """
    self._conn, conn = multiprocessing.Pipe()
    if xvfb:
      server_id = random.randint(10000, 99999)
      auth_file_id = random.randint(10000, 99999999999)

      xauthority_path = "/tmp/Xauthority_{}".format(auth_file_id)

      command = "Xvfb :{} -screen 0 1400x900x24 -nolisten tcp -auth {}".format(
          server_id, xauthority_path)
      with open(os.devnull, "w") as devnull:
        proc = subprocess.Popen(command.split(), shell=False, stdout=devnull,
                                stderr=devnull)
        atexit.register(lambda: os.kill(proc.pid, signal.SIGKILL))

      def constructor_using_xvfb():
        os.environ["DISPLAY"] = ":{}".format(server_id)
        os.environ["XAUTHORITY"] = xauthority_path
        return constructor()

      self._process = multiprocessing.Process(
          target=self._worker, args=(constructor_using_xvfb, conn))
    else:
      self._process = multiprocessing.Process(
          target=self._worker, args=(constructor, conn))

    atexit.register(self.close)
    self._process.start()
    self._observ_space = None
    self._action_space = None 
Example 73
Project: mx   Author: graalvm   File: mx.py    GNU General Public License v2.0 4 votes vote down vote up
def run_java_min_heap(args, benchName='# MinHeap:', overheadFactor=1.5, minHeap=0, maxHeap=2048, repetitions=1, out=None, err=None, cwd=None, timeout=None, env=None, addDefaultArgs=True, jdk=None):
    """computes the minimum heap size required to run a Java program within a certain overhead factor"""
    assert minHeap <= maxHeap

    def run_with_heap(heap, args, timeout=timeout, suppressStderr=True, nonZeroIsFatal=False):
        log('Trying with %sMB of heap...' % heap)
        with open(os.devnull, 'w') as fnull:
            vmArgs, pArgs = extract_VM_args(args=args, useDoubleDash=False, allowClasspath=True, defaultAllVMArgs=True)
            exitCode = run_java(vmArgs + ['-Xmx%dM' % heap] + pArgs, nonZeroIsFatal=nonZeroIsFatal, out=out, err=fnull if suppressStderr else err, cwd=cwd, timeout=timeout, env=env, addDefaultArgs=addDefaultArgs)
            if exitCode:
                log('failed')
            else:
                log('succeeded')
            return exitCode

    if overheadFactor > 0:
        t = time.time()
        if run_with_heap(maxHeap, args, timeout=timeout, suppressStderr=False):
            log('The reference heap (%sMB) is too low.' % maxHeap)
            return 1
        referenceTime = time.time() - t
        maxTime = referenceTime * overheadFactor
        log('Reference time = ' + str(referenceTime))
        log('Maximum time = ' + str(maxTime))
    else:
        maxTime = None

    currMin = minHeap
    currMax = maxHeap
    lastSuccess = maxHeap

    while currMax >= currMin:
        logv('Min = %s; Max = %s' % (currMin, currMax))
        avg = (currMax + currMin) / 2

        successful = 0
        while successful < repetitions:
            if run_with_heap(avg, args, timeout=maxTime):
                break
            else:
                successful += 1

        if successful == repetitions:
            lastSuccess = avg
            currMax = avg - 1
        else:
            currMin = avg + 1

    # We cannot bisect further. The last succesful attempt is the result.
    log('%s %s' % (benchName, lastSuccess)) 
Example 74
Project: audiogrep   Author: antiboredom   File: audiogrep.py    MIT License 4 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description='Audiogrep: splice together audio based on search phrases')

    parser.add_argument('--input', '-i', dest='inputfile', required=True, nargs='*', help='Source files to search through')
    parser.add_argument('--search', '-s', dest='search', help='Search term - to use a regular expression, use the -re flag')
    parser.add_argument('--regex', '-re', dest='regex', help='Use a regular expression for search', action='store_true')
    parser.add_argument('--output-mode', '-m', dest='outputmode', default='sentence', choices=['sentence', 'word', 'franken'], help='Splice together phrases, or single words, or "frankenstein" sentences')
    parser.add_argument('--output', '-o', dest='outputfile', default='supercut.mp3', help='Name of output file')
    parser.add_argument('--transcribe', '-t', dest='transcribe', action='store_true', help='Transcribe audio files')
    parser.add_argument('--extract', '-x', dest='extract', help='Extract all individual words from an audio file and write them to disk.', action='store_true')
    parser.add_argument('--padding', '-p', dest='padding', type=int, help='Milliseconds of padding between the audio segments')
    parser.add_argument('--crossfade', '-c', dest='crossfade', type=int, default=0, help='Crossfade between clips')
    parser.add_argument('--demo', '-d', dest='demo', action='store_true', help='Just display the search results without actually making the file')
    parser.add_argument('--layer', '-l', dest='layer', action='store_true', help='Overlay the audio segments')
    parser.add_argument('--json', '-j', dest='json', action='store_true', help='Output words to json')

    args = parser.parse_args()

    if not args.search and not args.transcribe and not args.json and not args.extract:
        parser.error('Please transcribe files [--transcribe] or search [--search SEARCH] already transcribed files')

    if args.transcribe:
        try:
            devnull = open(os.devnull)
            subprocess.Popen(['pocketsphinx_continuous', '--invalid-args'], stdout=devnull, stderr=devnull).communicate()
        except OSError as e:
            if e.errno == os.errno.ENOENT:
                print('Error: Please install pocketsphinx to transcribe files.')
                sys.exit()
        files = convert_to_wav(args.inputfile)
        transcribe(files)
    elif args.json:
        sentences = convert_timestamps(args.inputfile)
        print(words_json(sentences))

    elif args.search:
        if args.outputmode == 'franken':
            segments = franken_sentence(args.search, args.inputfile)
        else:
            segments = search(args.search, args.inputfile, mode=args.outputmode, regex=args.regex)

        if len(segments) == 0:
            print('No results for "' + args.search + '"')
            sys.exit()

        print('Generating supercut')
        if args.demo:
            for s in segments:
                if args.outputmode == 'sentence':
                    print(' '.join([w[0] for w in s['words']]))
                else:
                    print(s['words'])
        else:
            compose(segments, out=args.outputfile, padding=args.padding, crossfade=args.crossfade, layer=args.layer)
    elif args.extract:
        extract_words(args.inputfile) 
Example 75
Project: xia2   Author: xia2   File: XIA2Version.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def get_git_revision(fallback="not set"):
    """Try to obtain the current git revision number
    and store a copy in .gitversion"""
    version = None
    try:
        xia2_path = os.path.split(os.path.realpath(__file__))[0]
        version_file = os.path.join(xia2_path, ".gitversion")

        # 1. Try to access information in .git directory
        #    Regenerate .gitversion if possible
        if os.path.exists(os.path.join(xia2_path, ".git")):
            try:
                import subprocess

                def get_stdout(*popenargs, **kwargs):
                    """Run command with arguments and return stdout as a string.
                    Backported from Python 2.7 subprocess.check_output."""
                    with open(os.devnull, "w") as devnull:
                        process = subprocess.Popen(
                            stdout=subprocess.PIPE, *popenargs, stderr=devnull, **kwargs
                        )
                        output = process.communicate()[0]
                        assert not process.poll()
                        return output.rstrip().decode("latin-1")

                version = get_stdout(["git", "describe", "--long"], cwd=xia2_path)
                if version[0] == "v":
                    version = version[1:].replace(".0-", ".")
                try:
                    branch = get_stdout(
                        ["git", "describe", "--contains", "--all", "HEAD"],
                        cwd=xia2_path,
                    )
                    if (
                        branch != ""
                        and branch != "master"
                        and not branch.endswith("/master")
                    ):
                        version = version + "-" + branch
                except Exception:
                    pass
                with open(version_file, "w") as gv:
                    gv.write(version)
            except Exception:
                if version == "":
                    version = None

        # 2. If .git directory or git executable missing, read .gitversion
        if (version is None) and os.path.exists(version_file):
            with open(version_file, "r") as gv:
                version = gv.read().rstrip()
    except Exception:
        pass

    if version is None:
        version = fallback

    return str(version) 
Example 76
Project: pywren-ibm-cloud   Author: pywren   File: ibm_cf.py    Apache License 2.0 4 votes vote down vote up
def _generate_runtime_meta(self, docker_image_name):
        """
        Extract installed Python modules from docker image
        """
        action_code = """
            import sys
            import pkgutil

            def main(args):
                print("Extracting preinstalled Python modules...")
                runtime_meta = dict()
                mods = list(pkgutil.iter_modules())
                runtime_meta["preinstalls"] = [entry for entry in sorted([[mod, is_pkg] for _, mod, is_pkg in mods])]
                python_version = sys.version_info
                runtime_meta["python_ver"] = str(python_version[0])+"."+str(python_version[1])
                print("Done!")
                return runtime_meta
            """

        runtime_memory = 128
        # old_stdout = sys.stdout
        # sys.stdout = open(os.devnull, 'w')
        action_name = self._format_action_name(docker_image_name, runtime_memory)
        self.cf_client.create_package(self.package)
        self.cf_client.create_action(self.package, action_name, docker_image_name,
                                     is_binary=False, code=textwrap.dedent(action_code),
                                     memory=runtime_memory, timeout=30000)
        # sys.stdout = old_stdout
        logger.debug("Extracting Python modules list from: {}".format(docker_image_name))

        try:
            retry_invoke = True
            while retry_invoke:
                retry_invoke = False
                runtime_meta = self.cf_client.invoke_with_result(self.package, action_name)
                if 'activationId' in runtime_meta:
                    retry_invoke = True
        except Exception:
            raise("Unable to invoke 'modules' action")
        try:
            self.delete_runtime(docker_image_name, runtime_memory)
        except Exception:
            raise Exception("Unable to delete 'modules' action")

        if not runtime_meta or 'preinstalls' not in runtime_meta:
            raise Exception(runtime_meta)

        return runtime_meta 
Example 77
Project: pywren-ibm-cloud   Author: pywren   File: openwhisk.py    Apache License 2.0 4 votes vote down vote up
def _generate_runtime_meta(self, docker_image_name):
        """
        Extract installed Python modules from docker image
        """
        action_code = """
            import sys
            import pkgutil

            def main(args):
                print("Extracting preinstalled Python modules...")
                runtime_meta = dict()
                mods = list(pkgutil.iter_modules())
                runtime_meta["preinstalls"] = [entry for entry in sorted([[mod, is_pkg] for _, mod, is_pkg in mods])]
                python_version = sys.version_info
                runtime_meta["python_ver"] = str(python_version[0])+"."+str(python_version[1])
                print("Done!")
                return runtime_meta
            """

        runtime_memory = 128
        # old_stdout = sys.stdout
        # sys.stdout = open(os.devnull, 'w')
        action_name = self._format_action_name(docker_image_name, runtime_memory)
        self.cf_client.create_package(self.package)
        self.cf_client.create_action(self.package, action_name, docker_image_name,
                                     is_binary=False, code=textwrap.dedent(action_code),
                                     memory=runtime_memory, timeout=30000)
        # sys.stdout = old_stdout
        logger.debug("Extracting Python modules list from: {}".format(docker_image_name))

        try:
            retry_invoke = True
            while retry_invoke:
                retry_invoke = False
                runtime_meta = self.cf_client.invoke_with_result(self.package, action_name)
                if 'activationId' in runtime_meta:
                    retry_invoke = True
        except Exception:
            raise("Unable to invoke 'modules' action")
        try:
            self.delete_runtime(docker_image_name, runtime_memory)
        except Exception:
            raise Exception("Unable to delete 'modules' action")

        if not runtime_meta or 'preinstalls' not in runtime_meta:
            raise Exception(runtime_meta)

        return runtime_meta 
Example 78
Project: pywren-ibm-cloud   Author: pywren   File: executor.py    Apache License 2.0 4 votes vote down vote up
def clean(self, fs=None, local_execution=True):
        """
        Deletes all the files from COS. These files include the function,
        the data serialization and the function invocation results.
        """
        futures = self.futures if not fs else fs
        if type(futures) != list:
            futures = [futures]
        if not futures:
            return

        if not fs:
            present_jobs = {(f.executor_id, f.job_id) for f in futures
                            if (f.done or not f.produce_output)
                            and f.executor_id.count('/') == 1}
        else:
            present_jobs = {(f.executor_id, f.job_id) for f in futures
                            if f.executor_id.count('/') == 1}

        jobs_to_clean = present_jobs - self.cleaned_jobs

        if jobs_to_clean:
            msg = "ExecutorID {} - Cleaning temporary data".format(self.executor_id)
            logger.info(msg)
            if not self.log_level:
                print(msg)

        for executor_id, job_id in jobs_to_clean:
            storage_bucket = self.config['pywren']['storage_bucket']
            storage_prerix = '/'.join([JOBS_PREFIX, executor_id, job_id])

            if local_execution:
                # 1st case: Not background. The main code waits until the cleaner finishes its execution.
                # It is not ideal for performance tests, since it can take long time to complete.
                # clean_os_bucket(storage_bucket, storage_prerix, self.internal_storage)

                # 2nd case: Execute in Background as a subprocess. The main program does not wait for its completion.
                storage_config = json.dumps(self.internal_storage.get_storage_config())
                storage_config = storage_config.replace('"', '\\"')

                cmdstr = ('{} -c "from pywren_ibm_cloud.storage.utils import clean_bucket; \
                                  clean_bucket(\'{}\', \'{}\', \'{}\')"'.format(sys.executable,
                                                                                storage_bucket,
                                                                                storage_prerix,
                                                                                storage_config))
                os.popen(cmdstr)
            else:
                extra_env = {'STORE_STATUS': False,
                             'STORE_RESULT': False}
                old_stdout = sys.stdout
                sys.stdout = open(os.devnull, 'w')
                self.call_async(clean_os_bucket, [storage_bucket, storage_prerix], extra_env=extra_env)
                sys.stdout = old_stdout

        self.cleaned_jobs.update(jobs_to_clean) 
Example 79
Project: Caddy-X   Author: sayem314   File: caddyx.py    Apache License 2.0 4 votes vote down vote up
def Build():
	devnull = open(os.devnull,"w")
	cmd = "where" if whatos == "windows" else "which"
	checkgit = subprocess.call([cmd, 'git'], stdout=devnull, stderr=subprocess.STDOUT)
	if checkgit != 0:
		print(err, 'exec: "git": executable file not found in $PATH')
		exit()
	checkgo = subprocess.call([cmd, 'go'], stdout=devnull, stderr=subprocess.STDOUT)
	if checkgo != 0:
		print(err, 'exec: "go": executable file not found in $PATH')
		exit()

	# get caddy via go
	print("please wait. downloading latest source..")
	subprocess.call(['go', 'get', 'github.com/caddyserver/builds'])
	subprocess.call(['go', 'get', 'github.com/caddyserver/caddy'])
	os.chdir(caddygo + slash + 'caddymain')

	# Check if plugin need to be installed
	if len(sys.argv) == 3:
		if str(sys.argv[2]) in ["-p", "-P", "--plugin", "--plugins"]:
			print(err, "you did not pass any plugins to build")
			exit()
		else:
			print(str(sys.argv[2]), "is unknown parameter!")
			exit()
	if len(sys.argv) >= 3:
		if str(sys.argv[2]) in ["-p", "-P", "--plugin", "--plugins"]:
			plugins = (sys.argv[3].split(','))
			for word in plugins:
				AddPlugin(word)
		else:
			print(str(sys.argv[3]), "is not a valid argument!")
			exit()

	# build caddy web server
	os.chdir(caddygo)
	print("building caddy web server..")
	subprocess.call(['go', 'run', 'build.go'])
	if os.path.isfile("caddy"):
		os.rename("caddy", cwd + slash + "caddy")
		print(scs, "finised building:", cwd + slash + "caddy")
		exit()
	else:
		print(err, "are you sure all build tools is installed?")

# main commands! 
Example 80
Project: quickfix.py   Author: tonyxty   File: cli.py    MIT License 4 votes vote down vote up
def main(args=None):
    invocation = sys.argv[0]

    parser = get_parser()
    (options, args) = parser.parse_known_args(args)
    if invocation == "thefuck.py":
        options.fuck = True

    sys.argv[:] = args
    if len(args) > 0 and (args[0] == "python3" or args[0] == "python"):
        filename_index = 1
    else:
        filename_index = 0

    try:
        filename = args[filename_index]
    except IndexError:
        if options.fuck:
            print("#", end=" ")
        print("no file given")
        return 2

    if options.output is not None:
        exc = run(filename, options.interrupt)
    else:
        # suppress output of exec'ed script
        with open(os.devnull, "w") as f:
            with redirect_stdout(f):
                exc = run(filename, options.interrupt)

    if exc is not None:
        filename_filter = None if options.all else is_user_heuristic
        err_locs = extract_error_location(exc, filename_filter)
        if options.output is not None:
            outfile = open(options.output, "w")
        else:
            outfile = sys.stdout

        if options.fuck:
            try:
                filename, lineno, _ = next(err_locs)
            except StopIteration:
                print("# no fuck given", file=outfile)
            print(
                os.getenv("EDITOR", "sensible-editor")
                + " {} +{}".format(filename, lineno),
                file=outfile,
            )
        else:
            print(
                "\n".join('"{}":{}: {}'.format(*loc) for loc in err_locs),
                file=outfile,
            )

        if outfile is not sys.stdout:
            outfile.close()
        return 1
    return 0