• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python subprocess.getoutput函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中subprocess.getoutput函数的典型用法代码示例。如果您正苦于以下问题:Python getoutput函数的具体用法?Python getoutput怎么用?Python getoutput使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了getoutput函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: run_antechamber

def run_antechamber(molecule_name, input_filename, charge_method="bcc", net_charge=None, gaff_mol2_filename=None, frcmod_filename=None):
    """Run AmberTools antechamber and parmchk2 to create GAFF mol2 and frcmod files.

    Parameters
    ----------
    molecule_name : str
        Name of the molecule to be parameterized, will be used in output filenames.
    ligand_filename : str
        The molecule to be parameterized.  Must be tripos mol2 format.
    charge_method : str, optional
        If not None, the charge method string will be passed to Antechamber.
    net_charge : int, optional
        If not None, net charge of the molecule to be parameterized.
        If None, Antechamber sums up partial charges from the input file.
    gaff_mol2_filename : str, optional, default=None
        Name of GAFF mol2 filename to output.  If None, uses local directory
        and molecule_name
    frcmod_filename : str, optional, default=None
        Name of GAFF frcmod filename to output.  If None, uses local directory
        and molecule_name

    Returns
    -------
    gaff_mol2_filename : str
        GAFF format mol2 filename produced by antechamber
    frcmod_filename : str
        Amber frcmod file produced by prmchk
    """

    ext = parse_ligand_filename(input_filename)[1]

    filetype = ext[1:]
    if filetype != "mol2":
        raise(ValueError("Must input mol2 filename"))


    if gaff_mol2_filename is None:
        gaff_mol2_filename = molecule_name + '.gaff.mol2'
    if frcmod_filename is None:
        frcmod_filename = molecule_name + '.frcmod'

    cmd = "antechamber -i %s -fi mol2 -o %s -fo mol2 -s 2" % (input_filename, gaff_mol2_filename)
    if charge_method is not None:
        cmd += ' -c %s' % charge_method

    if net_charge is not None:
        cmd += ' -nc %d' % net_charge

    logger.debug(cmd)

    output = getoutput(cmd)
    logger.debug(output)

    cmd = "parmchk2 -i %s -f mol2 -o %s" % (gaff_mol2_filename, frcmod_filename)
    logger.debug(cmd)

    output = getoutput(cmd)
    logger.debug(output)

    return gaff_mol2_filename, frcmod_filename
开发者ID:kyleabeauchamp,项目名称:openmoltools,代码行数:60,代码来源:utils.py


示例2: cpu_check

def cpu_check():
    """
    TODO: split processor num / ssse3
    """
    ret = {
            "key": "cpu",
            "cn_desc": "cpu",
            }
    output = getoutput('cat /proc/cpuinfo').splitlines()
    # 某行类似processor : 3
    lines = [l for l in output if l.strip() and l.split()[0] == 'processor']
    cpu_num = len(lines)
    fail_standalone = False
    fail_cluster = False
    fail_reason = ""
    if cpu_num < CLUSTER_SYS_REQ['MIN_CPU_CORE_NUM']:
        fail_cluster |= True
        fail_reason = "集群版最低CPU核数:%d" % CLUSTER_SYS_REQ['MIN_CPU_CORE_NUM']
    if cpu_num < STANDALONE_SYS_REQ['MIN_CPU_CORE_NUM']:
        fail_standalone = True
        fail_reason = fail_reason + ", 单机版最低CPU核数:%d" % STANDALONE_SYS_REQ['MIN_CPU_CORE_NUM']
    support_ssse3 = len([l for l in output if 'flags' in l and 'ssse3' in l]) > 0
    fail_cluster |= not support_ssse3
    if not support_ssse3:
        fail_reason = fail_reason + ", 集群版要求CPU支持ssse3指令集"
    ret.update({
        "value": "processor num: %d, support ssse3: %r" % (cpu_num, support_ssse3),
        "pass_standalone": not fail_standalone,
        "pass_cluster": not fail_cluster,
        "fail_reason": fail_reason,
        "lscpu": getoutput("lscpu"),
        "proc_cpuinfo": getoutput("cat /proc/cpuinfo"),
        })
    return ret
开发者ID:liu2lin600,项目名称:linux_notes,代码行数:34,代码来源:20161216_sa_env_checker.py


示例3: create_db_image

def create_db_image(drucker):
    """Create database image from database container"""
    print(
        colorful.white_on_blue(
            "Committing %s image from %s container..."
            % (drucker.vars.DB_IMAGE, drucker.vars.DB_CONTAINER)
        )
    )

    subprocess.run(
        'docker commit -m "%s on %s" %s %s'
        % (
            drucker.vars.DB_CONTAINER,
            str(date.today()),
            drucker.vars.DB_CONTAINER,
            drucker.vars.DB_IMAGE,
        ),
        shell=True,
    )

    print(colorful.white_on_blue("Deleting initial container..."))
    subprocess.getoutput(
        "docker rm -f %s > /dev/null 2>&1" % (drucker.vars.DB_CONTAINER)
    )
    create_db_container(drucker)
开发者ID:anavarre,项目名称:drucker,代码行数:25,代码来源:db.py


示例4: run_pbs_jobs

def run_pbs_jobs(c, config_file, strategies_file, subject_list_file, p_name):



    import subprocess
    from time import strftime


    try:
        sublist = yaml.load(open(os.path.realpath(subject_list_file), 'r'))
    except:
        raise Exception ("Subject list is not in proper YAML format. Please check your file")
    
    temp_files_dir = os.path.join(os.getcwd(), 'cluster_temp_files')
    shell = subprocess.getoutput('echo $SHELL')
    subject_bash_file = os.path.join(temp_files_dir, 'submit_%s.pbs' % str(strftime("%Y_%m_%d_%H_%M_%S")))
    f = open(subject_bash_file, 'w')
    print('#! %s' % shell, file=f)
    print('#PBS -S %s' % shell, file=f)
    print('#PBS -V', file=f)
    print('#PBS -t 1-%d' % len(sublist), file=f)
    print('#PBS -q %s' % c.queue, file=f)
    print('#PBS -l nodes=1:ppn=%d' % c.numCoresPerSubject, file=f)
    print('#PBS -e %s' % os.path.join(temp_files_dir, 'c-pac_%s.err' % str(strftime("%Y_%m_%d_%H_%M_%S"))), file=f)
    print('#PBS -o %s' % os.path.join(temp_files_dir, 'c-pac_%s.out' % str(strftime("%Y_%m_%d_%H_%M_%S"))), file=f)
    print('source ~/.bashrc', file=f)

    print("python -c \"import CPAC; CPAC.pipeline.cpac_pipeline.run(\\\"%s\\\",\\\"%s\\\",\\\"${PBS_ARRAYID}\\\",\\\"%s\\\", \\\"%s\\\" , \\\"%s\\\", \\\"%s\\\", \\\"%s\\\") \" " % (str(config_file), \
        subject_list_file, strategies_file, c.maskSpecificationFile, c.roiSpecificationFile, c.templateSpecificationFile, p_name), file=f)
#    print >>f, "python -c \"import CPAC; CPAC.pipeline.cpac_pipeline.py -c %s -s %s -indx ${PBS_ARRAYID} -strategies %s \" " %(str(config_file), subject_list_file, strategies_file)
    #print >>f, "python CPAC.pipeline.cpac_pipeline.py -c ", str(config_file), "-s ", subject_list_file, " -indx ${PBS_ARRAYID} -strategies ", strategies_file
    f.close()

    subprocess.getoutput('chmod +x %s' % subject_bash_file )
开发者ID:ZheweiMedia,项目名称:DL_experiments,代码行数:34,代码来源:cpac_runner.py


示例5: menu

def menu():
	requestMenu = subprocess.getoutput("echo `zenity --list --title='PTTP' --text='What type of request do you want to make?' --column='Request type' 'GET' 'POST'`")
	requestMenu = requestMenu.split("\n")
	requestMenu = requestMenu[len(requestMenu) - 1]

	if requestMenu == "GET":
		#Do a GET request
		getMenu = subprocess.getoutput("echo `zenity --list --title='PTTP' --text='Authentication/response:' --column='Option' 'No authentication' 'Basic authentication' 'No authentication (plain text)' 'Basic authentication (plain text)'`")
		getMenu = getMenu.split("\n")
		getMenu = getMenu[len(getMenu) - 1]
		try:
			get(getMenu)
		except(urllib.error.HTTPError, urllib.error.URLError) as error:
			os.system("zenity --error --title='PTTP' --text='"+format(error)+"'")
		except:
			os.system("zenity --error --title='PTTP' --text='Oops! There was an error in your request.'")
	elif requestMenu == "POST":
		#Do a POST request
		postMenu = subprocess.getoutput("echo `zenity --list --title='PTTP' --text='Authentication/response:' --column='Option' 'No authentication' 'Basic authentication' 'No authentication (plain text)' 'Basic authentication (plain text)'`")
		postMenu = postMenu.split("\n")
		postMenu = postMenu[len(postMenu) - 1]
		try:
			post(postMenu)
		except(urllib.error.HTTPError, urllib.error.URLError) as error:
			os.system("zenity --error --title='PTTP' --text='"+format(error)+"'")
		except:
			os.system("zenity --error --title='PTTP' --text='Oops! There was an error in your request.'")
	else:
		sys.exit()
开发者ID:NickGeek,项目名称:pttp,代码行数:29,代码来源:pttp.py


示例6: _learn

 def _learn(self, irc, msg, channel, text, probability):
     """Internal method for learning phrases."""
     
     if os.path.exists(self._getBrainDirectoryForChannel(channel)):
         # Does this channel have a directory for the brain file stored and does this file exist?
         
         text = self._cleanText(text)
         
         if text and len(text) > 1 and not text.isspace():
     
             self.log.debug("Learning: {0}".format(text))
             cobeBrain = Brain(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'))
         
         text = self._cleanText(text)
         
         if text and len(text) > 1 and not text.isspace():
     
             self.log.debug("Learning: {0}".format(text))
             cobeBrain = Brain(self._getBrainDirectoryForChannel(channel))
             cobeBrain.learn(text)
             
             if random.randint(0, 10000) <= probability:
                 self._reply(irc, msg, channel, text)
开发者ID:waratte,项目名称:supybot,代码行数:31,代码来源:plugin.py


示例7: _update_repos

 def _update_repos(self):
     '''
     Prepare the reposiroties, return dict with repo information:
     {'<repo dir>': {'last_rev': '<last revision number>',
                      'files': '<list of files changed since last revision>'}
     '''
     repo_info = {}
     for base in self.roots:
         repo_info[base] = {}
         if not os.path.isdir(base):
             # checkout the repo
             co_cmd = 'svn co ' + self.roots[base] + ' ' + base
             lines = bytes.decode(subprocess.getoutput(co_cmd)).splitlines()
             repo_info[base]['last_rev'] = None
             repo_info[base]['files'] = self._find_pkgbuilds(base, lines)
         else:
             # Check the release numbers and run an update
             l_cmd = 'svn info ' + base + " | grep Revision: | awk '{print $2}'"
             l_rev = int(subprocess.getoutput(i_cmd).strip())
             repo_info['last_rev'] = str(l_rev)
             r_cmd = 'svn info ' + self.roots[base] + " | grep Revision: | awk '{print $2}'"
             r_rev = int(subprocess.getoutput(r_cmd).strip())
             if r_rev > l_rev:
                 # The local repo is out of date, update!
                 u_cmd = 'svn up ' + base
                 lines = bytes.decode(subprocess.getoutput(u_cmd)).splitlines()
                 repo_info[base]['files'] = self._find_pkgbuilds(base, lines)
     return repo_info
开发者ID:geekbuntu,项目名称:Quarters,代码行数:28,代码来源:svn.py


示例8: _resolution

 def _resolution(self):
     width=0
     heigth=0
     if(SystemInformations._platform(self) != "Windows"):            
         resolution = str(subprocess.getoutput("xrandr | grep connected"))
         resolution = re.sub("[a-z]*-[0-9]*", "", resolution)
         resolution = re.sub("\).*", "", resolution)
         resolution = re.sub("\+.* ", "", resolution)
         resolution = re.sub("[^0-9^\n]*", "", resolution)
         parseResolution = resolution.split("\n")
         for x in range(0, len(parseResolution)):
             if(width != 0):
                 if(parseResolution[x][0:4] != ""):
                     width=width+int(parseResolution[x][0:4])
             else:
                 if(parseResolution[x][0:4] != ""):
                     width=int(parseResolution[x][0:4])
                 
             if(heigth != 0):
                 if(parseResolution[x][4:9] != ""):
                     if(heigth < int(parseResolution[x][4:9])):
                         heigth = int(parseResolution[x][4:9])
             else:
                 if(parseResolution[x][4:9] != ""):
                     heigth=int(parseResolution[x][4:9])            
         
     else:
         resolution=re.sub("\n","",subprocess.getoutput("wmic path Win32_VideoController  get CurrentHorizontalResolution,CurrentVerticalResolution"))
         resolution=re.sub(" *","",resolution)
         resolution=re.sub("CurrentHorizontalResolution","",resolution)
         resolution=re.sub("CurrentVerticalResolution","",resolution)
         width=int(resolution[0:4])
         heigth=int(resolution[4:8])            
     totalResolution = str(width)+"x"+str(heigth)
     return totalResolution
开发者ID:Edmene,项目名称:O.G.B.Automation_Tool,代码行数:35,代码来源:system_info.py


示例9: test_nfs_getfacl

def test_nfs_getfacl():
	# mesures sur le getfacl
	test = RandomGen()

	path = '/mnt/nfs/test-acl' # NFS mounted directory
	u = subprocess.getoutput('rm ' + path + "/*")	# clean directory
	print("test acl getfacl\n")
	f = open('/tmp/acl-result-getfacl','w')
	for i in range(37):

		test.getUserList()
		testfile = 'testfile' + str(i)

		u = subprocess.getoutput('touch ' + path + "/" + testfile)
		print("setfacl " + str(i) + " " + u)
		for j in range(i):
			user = test.uList.pop()
			mode = test.createRandomMode()
			u = subprocess.getoutput('setfacl -m u:' + user + ':' + mode + " " + path + "/" + testfile)

		t1=time.time()
		u = subprocess.getoutput('getfacl ' + path + "/" + testfile)
		print("getfacl - " + str(i) + u + "\n")
		t2=time.time()
		f.write(str(i) + "\t" + str(t2-t1)+"\n")
		f.close()
开发者ID:kraj,项目名称:ltp,代码行数:26,代码来源:test_acl.py


示例10: library_install_objdump

def library_install_objdump(path, level):
    if path in skip_libs or path in done:
        return

    if level > 0:
        lib = find_dll(path)
        if lib == "":  # not found
            skip_libs.append(path)
            print("Not found: " + path)
            return
        print(lib)
        subprocess.getoutput("cp " + lib + " " + build_path)

    else:
        print("Processing target " + path)
        lib = path

    done.append(path)

    command = objdump_path + " -p " + lib + " | grep -o ': .*\.dll$'"
    res = subprocess.getstatusoutput(command)
    if (res[0] > 0):
        print("Error: objdump failed with " + lib)
    else:
        dlls = subprocess.getoutput(command).split("\n")
        for line in dlls:
            dll = (line.split(": "))[1]
            if dll not in done and dll not in skip_libs:
                level += 1
                library_install_objdump(dll, level)
开发者ID:AlisterH,项目名称:Quantum-GIS,代码行数:30,代码来源:deploy.py


示例11: test_acl_default

def test_acl_default(path):

# set default acl on the test directory
	u = subprocess.getoutput('mkdir ' + path + "/" + testdir)
	u = subprocess.getoutput('getfacl ' + path + "/" + testdir)
	acl=[]
	for i in range (len(splitedresult)-1):
		splitedline = splitedresult[i].split('::')
		name = splitedline[0]
		entry = splitedline[1]
		acl.append(name,entry)
# create a file in this directory
	u = subprocess.getoutput('touch ' + path + "/" + testdir + testfile)
# get the file's ACL and verify
	u = subprocess.getoutput('getfacl ' + path + "/" + testdir + testfile)
	splitedresult = u.split('\n')
	acl2=[]
	for i in range (len(splitedresult)-1):
		splitedline = splitedresult[i].split('::')
		name = splitedline[0]
		entry = splitedline[1]
		acl2.append(name,entry)

	result_final = True
	while i < len(acl2):
		result = False
		while j < len(acl2) and result == False:
			if acl2[i] == acl[j]:
				result = True
		if result == False:
			result_final = False
开发者ID:kraj,项目名称:ltp,代码行数:31,代码来源:test_acl.py


示例12: restruct_linux

def restruct_linux():
    qmake = sys.argv[3]
    # Copy the entire directory
    for d in ['bin', 'lib', 'libexec', 'share']:
        shutil.copytree(os.path.join(app_bundle, d), os.path.join(target_path, d), symlinks=True)

    # Copy Qt libs
    qtlibs_dir = subprocess.getoutput('%s -query QT_INSTALL_LIBS' % qmake).strip()
    for lib in ['Core', 'Gui', 'Widgets', 'Concurrent', 'Network', 'PrintSupport',
                'Qml', 'Quick', 'QuickWidgets', 'Xml', 'Svg', 'XcbQpa', 'Sql']:
        shutil.copy(os.path.join(qtlibs_dir, 'libQt5%s.so.5'%lib), lib_dir)

    # Copy Qt plugins
    qtplugins_dir = subprocess.getoutput('%s -query QT_INSTALL_PLUGINS' % qmake).strip()
    os.makedirs(plugins_dir)
    for plugin in ['bearer', 'designer', 'iconengines', 'imageformats',
                   'platforms', 'sqldrivers', 'xcbglintegrations']:
        shutil.copytree(os.path.join(qtplugins_dir, plugin), os.path.join(plugins_dir, plugin))
    # Copy QtQuick modules
    qtqml_dir = subprocess.getoutput('%s -query QT_INSTALL_QML' % qmake).strip()
    shutil.copytree(qtqml_dir, qml_dir)
    # Fix qt.conf
    open(os.path.join(bin_dir, 'qt.conf'), 'w').write('[Paths]\nPrefix = ..\n')
    open(os.path.join(libexec_dir, 'qtcreator', 'qt.conf'), 'w').write('[Paths]\nPrefix = ../..\n')
    # Fix rpath of qtcreator and executibles under libexec
    cmd = "chrpath -r '$ORIGIN/../lib/qtcreator:$ORIGIN/../lib:' " + os.path.join(bin_dir, 'qtcreator')
    os.system(cmd)
    for f in os.listdir(os.path.join(libexec_dir, 'qtcreator')):
        cmd = "chrpath -r '$ORIGIN/../../lib/qtcreator:$ORIGIN/../../lib:' " + os.path.join(libexec_dir, 'qtcreator', f)
        os.system(cmd)
开发者ID:xiaoqiangwang,项目名称:CSDataQuick,代码行数:30,代码来源:restruct_qtcreator.py


示例13: main

def main():
    print('Strated ---------------------')

    # execute(['ls', '-ls'])

    # proc = subprocess.Popen(['ls -lsa'], stdout = subprocess.PIPE, shell = True)
    # (out, err) = proc.communicate()
    # proc_status = proc.wait()
    # print("Command exit status: " + str(proc_status))
    # print("Command output: " + str(out))

    # output = subprocess.check_output('ls -ls', shell = True)
    # print(output)

    ip = '178.62.18.112'
    cmd = 'ssh-keygen -f ~/.ssh/known_hosts -R ' + ip
    print('CMD [' + cmd + ']')
    stdoutdata = subprocess.getoutput(cmd)
    print('------- OUTPUT START --------')
    print(stdoutdata)
    print('======= OUTPUT END   ========')

    cmd = 'echo -e \"Host ${myvmip}\n\tStrictHostKeyChecking no\n\" >> ~/.ssh/config'
    print('CMD [' + cmd + ']')
    stdoutdata = subprocess.getoutput(cmd)
    print('------- OUTPUT START --------')
    print(stdoutdata)
    print('======= OUTPUT END   ========')

    # s = pxssh.pxssh()
    # s.login()
    print('Finished --------------------')
开发者ID:kostaz,项目名称:DigitalOceanScripts,代码行数:32,代码来源:my_pxssh.py


示例14: GetProtoRuleFormattedData

  def GetProtoRuleFormattedData(cls, rule_data, out_type):
    """Get the formatted proto dependency info for the output type.

    Args:
      rule_data: dict: The rule data for the proto rule.
      out_type: string: The type for which the proto data is to be generated.

    Return:
      dict: Corresponding rules generated for the out_type.
    """
    srcs = rule_data.get('src', set())

    protobuf_base_dir = cls.GetProtoBufBaseDir();
    out = {}
    if out_type.find('cc_') == 0 :  # Generated cc rule.
      pkg_config_cmd = ('export PKG_CONFIG_PATH=%s; '
          'pkg-config --define-variable=prefix=%s protobuf' %
          (os.path.join(protobuf_base_dir, 'lib/pkgconfig'), protobuf_base_dir))

      out['src'] = set([ cls.__GetOutFileName(x, '.pb.cc') for x in srcs ])
      out['hdr'] = set([ cls.__GetOutFileName(x, '.pb.h') for x in srcs ])
      out['flag'] = set(subprocess.getoutput(pkg_config_cmd + ' --cflags').split())
      out['link'] = set(subprocess.getoutput(pkg_config_cmd + ' --libs').split())
    else:
      TermColor.Error('Unsupported referrer type %s' % out_type)

    return out
开发者ID:room77,项目名称:py77,代码行数:27,代码来源:proto_rules.py


示例15: tmux_layout

def tmux_layout():
    """Layout for gdb-dashboard using tmux panes"""
    # Bug? Cursor (in the terminal) is gone in any tmux pane after this function.
    panes_tty = subprocess.getoutput(["tmux lsp -F'#{pane_tty}'"]).split('\n')
    panes_id = subprocess.getoutput(["tmux lsp -F'#{pane_id}'"]).split('\n')
    print("panes_tty =", panes_tty)
    if len(panes_tty) == 2:
        # Put the outout in the right pane, and enable history and stacklocals
        gdb.execute("dashboard -layout !stacklocals stack history !threads source")
        # gdb.execute("dashboard -output " + panes_tty[1])
        # gdb.execute("dashboard stacklocals -output " + panes_tty[1])
        right_tty = panes_tty[1]
        gdb.execute("dashboard stack -output "   + right_tty)
        gdb.execute("dashboard history -output " + right_tty)
        gdb.execute("dashboard source -output "  + right_tty)
    if len(panes_tty) == 3:
        # NOTE: Execute tmux_split_gdb (from ~/.tmux_utils)
        gdb.execute("dashboard -layout stacklocals stack history !threads source")
        # gdb.execute("dashboard -output " + panes_tty[1])
        right_tty = panes_tty[2]
        up_index = 0
        up_tty = panes_tty[up_index]
        gdb.execute("dashboard stacklocals -output " + right_tty)
        gdb.execute("dashboard stack -output "       + right_tty)
        gdb.execute("dashboard history -output "     + right_tty)
        gdb.execute("dashboard source -output "      + up_tty)
        pane_source_height = subprocess.getoutput(["tmux lsp -F'#{pane_height}'"]).split('\n')[up_index]
        gdb.execute("dashboard source -style context " + str(int(int(pane_source_height)/2.1)))
开发者ID:phcerdan,项目名称:configuration_files,代码行数:28,代码来源:tmux-dashboard.py


示例16: commit

def commit():
    changes = subprocess.getoutput('git status -s')
    if not changes:
        return
    subprocess.call(['git', 'add', '--all', '.'])
    commitMsg = subprocess.getoutput('git status -s')
    subprocess.call(['git', 'commit', '-m', "{0}".format(commitMsg)])
开发者ID:mustcode,项目名称:gitask,代码行数:7,代码来源:repo.py


示例17: find_gateway

def find_gateway(interface):
    """
    Validate gateway on the system

    Ensures that the provided interface object is in fact configured as default
    route on the system.

    Returns gateway IP (reachable from interface) if default route is found,
    otherwise returns None.
    """

    address_family = interface.version
    output = subprocess.getoutput("ip -{} route".format(address_family))

    pattern = re.compile("default\s+via\s+(\S+)\s+")
    match = re.search(pattern, output)

    if match:
        gateway_ip = match.group(1)
        reverse_route_output = subprocess.getoutput("ip route get {}"
                                                    .format(gateway_ip))
        pattern = re.compile("{}.+src\s+{}".format(gateway_ip, interface.ip))
        if not re.search(pattern, reverse_route_output):
            logging.warning("Default route doesn't match iterface specified: {}"
                            .format(reverse_route_output))
            return None
        else:
            return gateway_ip
    else:
        logging.warning("Can't find gateway address on system")
        return None
开发者ID:fepan,项目名称:opnfv-apex-python,代码行数:31,代码来源:ip_utils.py


示例18: find

    def find(self, pkg, chkdistro, filelookup=True):
        _pkg = ''.join([x for x in pkg.strip().split(None,1)[0] if x.isalnum() or x in '.-_+/'])
        distro = ''
        if len(pkg.strip().split()) > 1:
            distro = ''.join([x for x in pkg.strip().split(None,2)[1] if x.isalnum() or x in '.-_+'])
        if not distro:
            distro = chkdistro
        if distro not in self.distros:
            return "%s is not a valid distribution: %s" % (distro, ", ".join(self.distros))
        pkg = _pkg

        data = subprocess.getoutput(self.aptcommand % (distro, distro, distro, distro, 'search -n', pkg))
        if not data:
            if filelookup:
                data = subprocess.getoutput(self.aptfilecommand % (distro, distro, pkg)).split()
                if data:
                    if data[0] == 'sh:': # apt-file isn't installed
                      self.log.error("PackageInfo/packages: apt-file is not installed")
                      return "Please use http://packages.ubuntu.com/ to search for files"
                    if data[0] == 'E:': # No files in the cache dir
                      self.log.error("PackageInfo/packages: Please run the 'update_apt_file' script")
                      return "Cache out of date, please contact the administrator"
                    if data[0] == "Use" and data[1] == "of":
                        url = "http://packages.ubuntu.com/search?searchon=contents&keywords=%s&mode=&suite=%s&arch=any" % (urllib.parse.quote(pkg), distro)
                        return url
                    if len(data) > 10:
                        return "File %s found in %s (and %d others) http://packages.ubuntu.com/search?searchon=contents&keywords=%s&mode=&suite=%s&arch=any" % (pkg, ', '.join(data[:10]), len(data)-10, urllib.parse.quote(pkg), distro)
                    return "File %s found in %s" % (pkg, ', '.join(data))
                return 'Package/file %s does not exist in %s' % (pkg, distro)
            return "No packages matching '%s' could be found" % pkg
        pkgs = [x.split()[0] for x in data.split('\n')]
        if len(pkgs) > 10:
            return "Found: %s (and %d others) http://packages.ubuntu.com/search?keywords=%s&searchon=names&suite=%s&section=all" % (', '.join(pkgs[:10]), len(pkgs)-10, urllib.parse.quote(pkg), distro)
        else:
            return "Found: %s" % ', '.join(pkgs[:5])
开发者ID:mapreri,项目名称:MPR-supybot,代码行数:35,代码来源:packages.py


示例19: deployQtLibraries

def deployQtLibraries():
    libs = ['Core', 'Gui', 'Widgets', 'Concurrent', 'Network', 'PrintSupport', 'Script',
            'Qml', 'Quick', 'QuickWidgets', 'QuickControls2', 'QuickTemplates2', 'QuickParticles',
            'Xml', 'Svg', 'Sql', 'Help']
    qtlibs_dir = subprocess.getoutput('%s -query QT_INSTALL_LIBS' % qmake).strip()
    dst_dir = lib_dir
    lib_pattern = 'libQt5%s.so*'
    ignore_pattern = None

    if platform.system() == 'Darwin':
        lib_pattern = 'Qt%s.framework'
        ignore_pattern = shutil.ignore_patterns('Headers', '*_debug', '*.prl')
    elif platform.system() == 'Windows':
        qtlibs_dir = subprocess.getoutput('%s -query QT_INSTALL_BINS' % qmake).strip()
        dst_dir = bin_dir
        lib_pattern = 'Qt5%s.dll'
    elif platform.system() == 'Linux':
        libs += ['XcbQpa']

    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)

    for lib in libs:
        for file in glob.glob(os.path.join(qtlibs_dir, lib_pattern%lib)):
            smartCopy(file, dst_dir, follow_symlinks=False, ignore=ignore_pattern)

    if platform.system() == 'Windows':
        for lib in ['libEGL.dll', 'libGLESv2.dll']:
            smartCopy(os.path.join(qtlibs_dir, lib), dst_dir)
开发者ID:xiaoqiangwang,项目名称:CSDataQuick,代码行数:29,代码来源:fixup_qtcreator.py


示例20: scamper_call

    def scamper_call(self,IP_name,arguments):
        if arguments=='':
            whole=subprocess.getoutput('scamper -i '+IP_name)
        else:
            arguments='"trace '+arguments+' '+IP_name+'"'
            try:
                whole=subprocess.getoutput('scamper -I '+arguments)
            except:
                print('Scamper failed to traceroute. Exiting.')
                exit(0)

        splitted=whole.split('\n')
        rows=len(splitted)-1
        route=[0 for x in range(0,rows)]
        mytime=['-' for x in range(0,rows)]

        for i in range (1,rows+1):
            pos=0
            temp=splitted[i].split(' ')
            while temp[pos]=='':
                pos=pos+1
            if i>0:
                route[i-1]=temp[pos+2]
            
                if len(temp)>pos+4:
                    mytime[i-1]=temp[pos+4]+' '+temp[pos+5]
            i=i+1

        return [route,mytime]
开发者ID:santiagorr,项目名称:traIXroute,代码行数:29,代码来源:trace_tool.py



注:本文中的subprocess.getoutput函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python subprocess.getstatusoutput函数代码示例发布时间:2022-05-27
下一篇:
Python subprocess.execute函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap