Python subprocess.getoutput() Examples

The following are 30 code examples of subprocess.getoutput(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module subprocess , or try the search function .
Example #1
Source File: test_subprocess.py    From Fluid-Designer with GNU General Public License v3.0 7 votes vote down vote up
def test_getoutput(self):
        self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
        self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
                         (0, 'xyzzy'))

        # we use mkdtemp in the next line to create an empty directory
        # under our exclusive control; from that, we can invent a pathname
        # that we _know_ won't exist.  This is guaranteed to fail.
        dir = None
        try:
            dir = tempfile.mkdtemp()
            name = os.path.join(dir, "foo")
            status, output = subprocess.getstatusoutput(
                ("type " if mswindows else "cat ") + name)
            self.assertNotEqual(status, 0)
        finally:
            if dir is not None:
                os.rmdir(dir) 
Example #2
Source File: utils.py    From Actor-Critic-Based-Resource-Allocation-for-Multimodal-Optical-Networks with GNU General Public License v3.0 6 votes vote down vote up
def parse_log(file):
    """
    解析log文件,画出阻塞率的变化曲线
    :param file:
    :return:
    """
    prefix = 'bash'
    log_file = os.path.join(prefix, file)
    out = sp.getoutput("cat {}| grep remain".format(log_file))
    out = out.split('\n')
    y = []
    for i in out:
        tmp = i.split(' ')[26]
        tmp = tmp.split('=')[1]
        y.append(float(tmp))
    plt.plot(y) 
Example #3
Source File: operator_install.py    From hpe-solutions-openshift with Apache License 2.0 6 votes vote down vote up
def get_token(oc_path):
    """
    Get authentication token from OC command line tool

    Returns:
    The bearer token to the init_setup function

    """
    global USER_NAME, PASSWORD, IP
    print("Logging into your OpenShift Cluster")
    status, _ = subprocess.getstatusoutput(oc_path + "oc login "+IP+" -u "+USER_NAME+" -p "+ \
        PASSWORD +" --insecure-skip-tls-verify=true")
    if status == 0:
        print("Successfully logged into the OpenShift Cluster")
    else:
        print("Could not login, please enter correct login credentials")
        exit(1)
    token = subprocess.getoutput(oc_path + "oc whoami -t")

    return token

#General Function for get calls 
Example #4
Source File: test_subprocess.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_getoutput(self):
        self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
        self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
                         (0, 'xyzzy'))

        # we use mkdtemp in the next line to create an empty directory
        # under our exclusive control; from that, we can invent a pathname
        # that we _know_ won't exist.  This is guaranteed to fail.
        dir = None
        try:
            dir = tempfile.mkdtemp()
            name = os.path.join(dir, "foo")
            status, output = subprocess.getstatusoutput(
                ("type " if mswindows else "cat ") + name)
            self.assertNotEqual(status, 0)
        finally:
            if dir is not None:
                os.rmdir(dir) 
Example #5
Source File: Gowitness.py    From armory with GNU General Public License v3.0 6 votes vote down vote up
def process_output(self, cmds):
        """
        Not really any output to process with this module, but you need to cwd into directory to make database generation work, so
        I'll do that here.
        """

        cwd = os.getcwd()
        ver_pat = re.compile("gowitness:\s?(?P<ver>\d+\.\d+\.\d+)")
        version = subprocess.getoutput("gowitness version")
        command_change = LooseVersion("1.0.8")
        gen_command = ["report", "generate"]
        m = ver_pat.match(version)
        if m:
            if LooseVersion(m.group("ver")) <= command_change:
                gen_command = ["generate"]
        for cmd in cmds:
            output = cmd["output"]

            cmd = [self.binary] + gen_command
            os.chdir(output)

            subprocess.Popen(cmd, shell=False).wait()
            os.chdir(cwd)

        self.IPAddress.commit() 
Example #6
Source File: plugin.py    From limnoria-plugins with Do What The F*ck You Want To Public License 6 votes vote down vote up
def _learn(self, irc, msg, channel, text, probability):
        """Internal method for learning phrases."""
        text = self._processText(channel, text)  # Run text ignores/strips/cleanup.
        if os.path.exists(self._getBrainDirectoryForChannel(channel)):
            # Does this channel have a directory for the brain file stored and does this file exist?
            if text:
                self.log.debug("Learning: {0}".format(text))
                cobeBrain = SQLiteBrain(self._getBrainDirectoryForChannel(channel))
                cobeBrain.learn(text)
                if random.randint(0, 10000) <= probability:
                    self._reply(irc, msg, channel, text)
        else:  # Nope, let's make it!
            subprocess.getoutput("{0} {1}".format(self._doCommand(channel), "init"))
            if text:
                self.log.debug("Learning: {0}".format(text))
                cobeBrain = SQLiteBrain(self._getBrainDirectoryForChannel(channel))
                cobeBrain.learn(text)
                if random.randint(0, 10000) <= probability:
                    self._reply(irc, msg, channel, text) 
Example #7
Source File: tasks.py    From OasisPlatform with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_worker_versions():
    """ Search and return the versions of Oasis components
    """
    ktool_ver_str = subprocess.getoutput('fmcalc -v')
    plat_ver_file = '/home/worker/VERSION'

    if os.path.isfile(plat_ver_file):
        with open(plat_ver_file, 'r') as f:
            plat_ver_str = f.read().strip()
    else:
        plat_ver_str = ""

    return {
        "oasislmf": mdk_version,
        "ktools": ktool_ver_str,
        "platform": plat_ver_str
    }


# When a worker connects send a task to the worker-monitor to register a new model 
Example #8
Source File: core.py    From chepy with GNU General Public License v3.0 6 votes vote down vote up
def load_command(self):  # pragma: no cover
        """Run the command in state and get the output
        
        Returns:
            Chepy: The Chepy object. 

        Examples:
            This method can be used to interace with the shell and Chepy 
            directly by ingesting a commands output in Chepy. 

            >>> c = Chepy("ls -l").shell_output().o
            test.html
            ...
            test.py
        """
        self.state = subprocess.getoutput(self.state)
        return self 
Example #9
Source File: saram.py    From saram with MIT License 5 votes vote down vote up
def get_rotation_info(self, filename):
        arguments = ' %s - -psm 0'
        stdoutdata = subprocess.getoutput('tesseract' + arguments % filename)
        degrees = None

        for line in stdoutdata.splitlines():
            print(line)
            info = 'Orientation in degrees: '
            if info in line:
                degrees = -float(line.replace(info, '').strip())
        return degrees 
Example #10
Source File: pykms_GuiBase.py    From py-kms with The Unlicense 5 votes vote down vote up
def get_ip_address():
        if os.name == 'posix':
                try:
                        # Python 2.x import
                        import commands 
                except ImportError:
                        #Python 3.x import
                        import subprocess as commands 
                ip = commands.getoutput("hostname -I")
        elif os.name == 'nt':
                import socket
                ip = socket.gethostbyname(socket.gethostname())
        else:
                ip = 'Unknown'
        return ip 
Example #11
Source File: env.py    From kaggle-kuzushiji-recognition with MIT License 5 votes vote down vote up
def _init_dist_slurm(backend, port=29500, **kwargs):
    proc_id = int(os.environ['SLURM_PROCID'])
    ntasks = int(os.environ['SLURM_NTASKS'])
    node_list = os.environ['SLURM_NODELIST']
    num_gpus = torch.cuda.device_count()
    torch.cuda.set_device(proc_id % num_gpus)
    addr = subprocess.getoutput(
        'scontrol show hostname {} | head -n1'.format(node_list))
    os.environ['MASTER_PORT'] = str(port)
    os.environ['MASTER_ADDR'] = addr
    os.environ['WORLD_SIZE'] = str(ntasks)
    os.environ['RANK'] = str(proc_id)
    dist.init_process_group(backend=backend) 
Example #12
Source File: EnvirTools.py    From Sniffer with MIT License 5 votes vote down vote up
def autoFix(Name):
    exitflag = 0
    print('[Uninstalled] %s' %(', '.join(Name)))
    
    if input('[+]Maybe you want me to fix it? [y/n] ') != 'y':
        return False
    
    for name in Name:
        try:
            print('  [-]Install %s... ' %name,)
            sys.stdout.flush()
            result = subprocess.getoutput('sudo pip3 install %s' %name)
            if 'Successfully installed' in result:
                print('Successfully!')
            else:
                print('[Failed] You should install %s by yourself :(' %name)
                exitflag = 1
                
        except Exception as e:
            print('[!]Oops, Failed! You should fix it by yourself. Sorry :(')
            print('  [-]Error:', e, '\n')
            return False
    
    if exitflag: return False
    from termcolor import colored
    print('[*]' + colored('All Done!', color = 'green', attrs = ['bold']), '\n')
    return True 
Example #13
Source File: tests.py    From budgie-wallpapers with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def test_output(self):
        output = subprocess.getoutput('python3 update_background.py')
        self.assertEqual(output, update_background.get_output()) 
Example #14
Source File: env.py    From RDSNet with Apache License 2.0 5 votes vote down vote up
def _init_dist_slurm(backend, port=29500, **kwargs):
    proc_id = int(os.environ['SLURM_PROCID'])
    ntasks = int(os.environ['SLURM_NTASKS'])
    node_list = os.environ['SLURM_NODELIST']
    num_gpus = torch.cuda.device_count()
    torch.cuda.set_device(proc_id % num_gpus)
    addr = subprocess.getoutput(
        'scontrol show hostname {} | head -n1'.format(node_list))
    os.environ['MASTER_PORT'] = str(port)
    os.environ['MASTER_ADDR'] = addr
    os.environ['WORLD_SIZE'] = str(ntasks)
    os.environ['RANK'] = str(proc_id)
    dist.init_process_group(backend=backend) 
Example #15
Source File: tests.py    From budgie-wallpapers with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def test_output(self):
        output = subprocess.getoutput('python3 update_properties.py')
        self.assertEqual(output, update_properties.get_output()) 
Example #16
Source File: env.py    From IoU-Uniform-R-CNN with Apache License 2.0 5 votes vote down vote up
def _init_dist_slurm(backend, port=29500, **kwargs):
    proc_id = int(os.environ['SLURM_PROCID'])
    ntasks = int(os.environ['SLURM_NTASKS'])
    node_list = os.environ['SLURM_NODELIST']
    num_gpus = torch.cuda.device_count()
    torch.cuda.set_device(proc_id % num_gpus)
    addr = subprocess.getoutput(
        'scontrol show hostname {} | head -n1'.format(node_list))
    os.environ['MASTER_PORT'] = str(port)
    os.environ['MASTER_ADDR'] = addr
    os.environ['WORLD_SIZE'] = str(ntasks)
    os.environ['RANK'] = str(proc_id)
    dist.init_process_group(backend=backend) 
Example #17
Source File: testautoRIFT.py    From autoRIFT with Apache License 2.0 5 votes vote down vote up
def runCmd(cmd):
    import subprocess
    out = subprocess.getoutput(cmd)
    return out 
Example #18
Source File: test.py    From bioinformatics_primer with MIT License 5 votes vote down vote up
def test_usage():
    """usage"""

    for flag in ['', '-h', '--help']:
        out = getoutput('{} {}'.format(prg, flag))
        assert re.match("usage", out, re.IGNORECASE)


# -------------------------------------------------- 
Example #19
Source File: test.py    From bioinformatics_primer with MIT License 5 votes vote down vote up
def test_usage():
    """usage"""

    for flag in ['', '-h', '--help']:
        out = getoutput('{} {}'.format(prg, flag))
        assert re.match("usage", out, re.IGNORECASE)


# -------------------------------------------------- 
Example #20
Source File: test.py    From bioinformatics_primer with MIT License 5 votes vote down vote up
def test_head_run():
    """runs ok"""

    for (file, num) in [("files/sonnet-29.txt", 3), ("files/issa.txt", 10)]:
        out = getoutput("{} {} {}".format(prg, file, num))
        expected = head_file(file, num)
        assert out.rstrip() == expected.rstrip() 
Example #21
Source File: test.py    From bioinformatics_primer with MIT License 5 votes vote down vote up
def test_usage():
    """usage"""

    for flag in ['', '-h', '--help']:
        out = getoutput('{} {}'.format(prg, flag))
        assert re.match("usage", out, re.IGNORECASE)


# -------------------------------------------------- 
Example #22
Source File: test.py    From bioinformatics_primer with MIT License 5 votes vote down vote up
def test_accept_02():
    out = getoutput('{} MRY'.format(prg))
    expected = """
pattern = "MRY"
regex   = "^[AC][AG][CT]$"
AAC OK
AAT OK
AGC OK
AGT OK
CAC OK
CAT OK
CGC OK
CGT OK
    """.strip()
    assert out.strip() == expected 
Example #23
Source File: test.py    From bioinformatics_primer with MIT License 5 votes vote down vote up
def test_usage():
    """usage"""

    for flag in ['', '-h', '--help']:
        out = getoutput('{} {}'.format(prg, flag))
        assert re.match("usage", out, re.IGNORECASE)


# -------------------------------------------------- 
Example #24
Source File: test.py    From bioinformatics_primer with MIT License 5 votes vote down vote up
def test_runs():
    """runs ok"""
    for file in [sonnet, issa]:
        for num in [1, 3, 5, 9]:
            out = getoutput("{} {} {}".format(prg, file, num))
            out_lines = out.split('\n')
            assert len(out_lines) == num 
Example #25
Source File: test.py    From bioinformatics_primer with MIT License 5 votes vote down vote up
def test_usage():
    """ usage """

    for flag in ['', '-h', '--help']:
        out = getoutput('{} {}'.format(prg, flag))
        assert re.match("usage", out, re.IGNORECASE)


# -------------------------------------------------- 
Example #26
Source File: test.py    From bioinformatics_primer with MIT License 5 votes vote down vote up
def test_bad_input():
    """fails on bad input"""
    year, month, day, hour, minute, sec = gen_date()
    sep = random.choice(list('!@@#$%^&*():[]:;/?,.~|'))
    out = getoutput('{} "{}"'.format(prg, sep.join(map(str,
                                                     [year, month, day]))))
    assert out == 'No match' 
Example #27
Source File: test.py    From bioinformatics_primer with MIT License 5 votes vote down vote up
def test_10():
    """December-2015"""

    for _ in range(num_tests):
        year, month, day, hour, minute, sec = gen_date(month='long')
        sep = ', ' if random.choice([0, 1]) else '-'
        out = getoutput('{} "{}{}{}"'.format(prg, month, sep, year))
        d = dict(map(reversed, enumerate(long, 1)))
        expected = '{}-{:02d}-01'.format(year, d[month])
        assert out == expected


# -------------------------------------------------- 
Example #28
Source File: test.py    From bioinformatics_primer with MIT License 5 votes vote down vote up
def test_08():
    """2/14-12/15"""

    for _ in range(num_tests):
        year1, month1, day1, hour1, minute1, sec1 = gen_date()
        year2, month2, day2, hour2, minute2, sec2 = gen_date()
        year1 = str(year1)[2:]
        year2 = str(year1)[2:]
        out = getoutput('{} {}/{}-{}/{}'.format(prg, month1, year1, month2,
                                                year2))
        expected = '20{:02d}-{:02d}-01'.format(int(year1), month1)
        assert out == expected


# -------------------------------------------------- 
Example #29
Source File: test.py    From bioinformatics_primer with MIT License 5 votes vote down vote up
def test_07():
    """12/06"""

    for _ in range(num_tests):
        year, month, day, hour, minute, sec = gen_date()
        year = str(year)[2:]
        out = getoutput('{} {}/{}'.format(prg, month, year))
        expected = '20{:02d}-{:02d}-01'.format(int(year), month)
        assert out == expected


# -------------------------------------------------- 
Example #30
Source File: test.py    From bioinformatics_primer with MIT License 5 votes vote down vote up
def test_06():
    """2015-01-03/2015-02-14"""

    for _ in range(num_tests):
        year1, month1, day1, hour1, minute1, sec1 = gen_date()
        year2, month2, day2, hour2, minute2, sec2 = gen_date()
        dt = '{}-{}-{}/{}-{}-{}'.format(year1, month1, day1, year2, month2,
                                        day2)
        out = getoutput('{} {}'.format(prg, dt))
        expected = '{:02d}-{:02d}-{:02d}'.format(year1, month1, day1)
        assert out == expected


# --------------------------------------------------