当前位置: 首页>>代码示例>>Python>>正文


Python Popen.readlines方法代码示例

本文整理汇总了Python中subprocess.Popen.readlines方法的典型用法代码示例。如果您正苦于以下问题:Python Popen.readlines方法的具体用法?Python Popen.readlines怎么用?Python Popen.readlines使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在subprocess.Popen的用法示例。


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

示例1: getZpoolDevs

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import readlines [as 别名]
def getZpoolDevs(ml=None, zl=None):
    mpdevs = []
    zpools = []

    if not ml or not zl:
        ml = Popen(['/usr/sbin/mpathadm','list', 'LU'], stdout=PIPE).stdout
        zl = Popen(['/usr/sbin/zpool','status'], env={'LC_ALL':'C'}, stdout=PIPE).stdout
    mpdevs = [ (line.strip()) for line in ml.readlines() if 'rdsk' in line]
    
    lines = zl.readlines()
    iter_lines = iter(lines)
    devpat = compile('(/dev/(r)?dsk/)?(c.*d0)(s[0-9])?')
    for line in iter_lines:
        if 'pool:' in line:
            zd = {}
            poolname = line.split()[1]
            zd[poolname] = []
            for line in iter_lines:
                if len(line.split()) > 4:
                    if  line.split()[0] in ('errors:'):
                        break
                    if  line.split()[0] in (poolname,'mirror-0', 'NAME', 'scan:'):
                        continue
                    if match(devpat, line.split()[0]):
                        for d in mpdevs:
                            if match(devpat, line.split()[0]).groups()[2] == match(devpat, d).groups()[2]:
                                zd[poolname].append(d)
                                break

            zpools.append(zd)
    return zpools
开发者ID:cgrzemba,项目名称:dskdisp,代码行数:33,代码来源:dskdisp.py

示例2: runshell

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import readlines [as 别名]
 def runshell(input):
     """
     This function just calls popen on the input string, and the stdout is printed.
     """
     from pyina import mpi
     from subprocess import Popen, PIPE
     print "%d of %d: executing: %s" % (mpi.world.rank, mpi.world.size, input)
     pipe = Popen(input, shell=True, stdout=PIPE).stdout
     pipe.readlines()
     return 0
开发者ID:hpparvi,项目名称:pyina,代码行数:12,代码来源:test_parallelmap.py

示例3: save

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import readlines [as 别名]
    def save(self,filename=None):
        start = time.time()
        if filename is None:
            filename = self._genfilename()

        cmd = ' '.join([gspath,
                            '-dNOPAUSE',
                            '-q',
                            '-r300',
                            '-sDEVICE=tiffg4',
                            '-dBATCH',
                            '-sOutputFile=%s'%filename,
                            '-sPAPERSIZE=a4',
                            '-dFirstPage=%d'%self._pagenumber,
                            '-dLastPage=%d'%self._pagenumber,
                            self._origfile
                        ])
        po = Popen(cmd,shell=True,stdout=PIPE,stderr=STDOUT).stdout
        for l in po.readlines():
            self._l.debug("GS Output:%s",l)
        po.close()
        self._file = filename
        self._l.debug("Saving file %s (duration %f)",
                      filename,(time.time()-start))
        return filename
开发者ID:svrist,项目名称:preomr,代码行数:27,代码来源:convlib.py

示例4: get_svn_info

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import readlines [as 别名]
def get_svn_info():
    "Check the status of the target directories for svn checkouts"
    logger(get_func_name() + "()", "debug")
    global relCfg
    exit_status = 0

    if 'SVN' in relCfg:
        for line in relCfg['SVN'] :
            if (os.access(line[0] + "/.svn", os.W_OK)
                and os.path.isdir(line[0] + "/.svn")):
                line.append('svn')
                p = Popen( ('/usr/bin/svn info ' + line[0]), shell=True, stdout=PIPE).stdout
                plines = filter(None, [pline.strip() for pline in p.readlines()])
                for pline in plines:
                    k, v = re.split(': ', pline, 1)
                    if (k == 'URL'):
                        line.append(v)
                    if (k == 'Revision'):
                        line.append(v)

            elif (os.access(line[0], os.W_OK)
                and os.path.isdir(line[0])):
                line.append('dir')
            else:
                line.append('bad')
                exit_status = -1
    else:
        exit_status = -1

    return exit_status
开发者ID:DanRode,项目名称:misc,代码行数:32,代码来源:csctrl.py

示例5: scanEntries

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import readlines [as 别名]
    def scanEntries(self):
        assert self.isArchive()

        attrs = self.attrs
        attrs = attrs.dirAttrs

        attrs.thisCount  = 0
        attrs.thisSize   = 0
        attrs.totalCount = 0
        attrs.totalSize  = 0

        pipe = None

        try:
            pipe = Popen("7za l \"%s\"" % self.path, shell = True,
                         stdout = PIPE).stdout

            for line in pipe.readlines():
                if not re.match("20", line):
                    continue

                filename = line[53:-1]

                entry = Entry(self.volume, self, join(self.path, filename),
                              join(self.volumePath, filename), filename)
                self.readStoredInfo(entry, line)
                entry.store()

                attrs.thisCount += 1
                attrs.thisSize  += entry.attrs.size
        except Exception, msg:
            print "Failed to index %s:" % self.path, msg
开发者ID:jwiegley,项目名称:disk-catalog,代码行数:34,代码来源:catalog.py

示例6: __init__

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import readlines [as 别名]
class LineReader:
    def __init__(self, fname):
        if fname.endswith(".gz"):
            if not os.path.isfile(fname):
                raise IOError(fname)
            self.f = Popen(["gunzip", "-c", fname], stdout=PIPE, stderr=PIPE)
            self.zipped = True
        else:
            self.f = open(fname, "r")
            self.zipped = False

    def readlines(self):
        if self.zipped:
            for line in self.f.stdout:
                yield line
        else:
            for line in self.f.readlines():
                yield line

    def close(self):
        if self.zipped:
            if self.f.poll() == None:
                os.kill(self.f.pid, signal.SIGHUP)
        else:
            self.f.close()

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.close()

    def __iter__(self):
        return self.readlines()
开发者ID:Kortemme-Lab,项目名称:klab,代码行数:36,代码来源:zip_util.py

示例7: fingerprint

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import readlines [as 别名]
def fingerprint(source=None):
  """Create a new fingerprint of current repositories.

  The source argument is parsed to look for the expected output
  from a `sync-all` command. If the source is `None` then the
  `sync-all` command will be run to get the current fingerprint.
  """
  if source is None:
    if sys.platform == 'win32':
      # Can't rely on perl being located at `/usr/bin/perl`.
      sync_all = ["perl", "./sync-all", "log", "-1", "--pretty=oneline"]
    else:
      sync_all = ["./sync-all", "log", "-1", "--pretty=oneline"]

    source = Popen(sync_all, stdout=PIPE).stdout

  lib = ""
  commits = {}
  for line in source.readlines():
    if line.startswith("=="):
      lib = line.split()[1].rstrip(":")
      lib = "." if lib == "running" else lib # hack for top ghc repo
    elif re.match("[abcdef0-9]{40}", line):
      commit = line[:40]
      commits[lib] = commit
  return FingerPrint(commits)
开发者ID:DavidAlphaFox,项目名称:ghc,代码行数:28,代码来源:fingerprint.py

示例8: _hostIsUp

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import readlines [as 别名]
def _hostIsUp(host, count=1, timeout=1):
    """
    Executes a ping command and sets the appropriate attribute.
    Parameters: A host, optional: Amount of pings, Timeout
    
    """
    
    thecommand = 'ping -n {0} -w {1} -a {2}'.format(count, timeout, host.ipaddress)
    
    results = Popen(thecommand, stdout=PIPE).stdout
    output = results.readlines()
    results.close()
    
    # Convert the returned bytearrays to strings.
    output = [item.decode('utf8') for item in output]
    output = ' '.join(output)

    if ('Request timed out' in output) or ('Destination net unreachable' in output):
        if host.isup == True:
            host.isup = False
            host.changed = True
    else:
        if host.isup == False:
            host.isup = True
            host.changed = True
开发者ID:bdubyapee,项目名称:mip5000-manager,代码行数:27,代码来源:mthreadping.py

示例9: run_one

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import readlines [as 别名]
 def run_one(self, prot_p):
     ###print self.name + ' Running :' + prot_p
     cmdline = "{0} {1}".format(psipred_exe, prot_p)
     result = Popen(cmdline, shell=True, stdout=PIPE).stdout
     for line in result.readlines():
         # print line
         if str(line).find("Finished.") != -1:
             ###print self.name + ' Finished :' + prot_p
             return 1
开发者ID:jakebarnwell,项目名称:PythonGenerator,代码行数:11,代码来源:pred_sec_struct.py

示例10: stanfordTag

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import readlines [as 别名]
def stanfordTag(text):
        text = text.replace('\n','. ')
        text = text.encode('ascii','ignore')
        data=open(directory+'data.txt','w')
        print(text,end='',file=data)
        data.close()
        file=Popen("cd "+STANFORD_PATH+"; ./stanford-postagger.sh models/wsj-0-18-bidirectional-nodistsim.tagger "+directory+"data.txt", shell=True, stdout=PIPE).stdout
        sentences=file.readlines()
        postagged = [[tuple(word.split('_')) for word in sentence] for sentence in [sent.split(' ') for sent in sentences]]
        return postagged
开发者ID:intabeta,项目名称:inta,代码行数:12,代码来源:keywords.py

示例11: notifier_loop_callback

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import readlines [as 别名]
    def notifier_loop_callback(self, notifier):
        if len(self.file_events) > 0:
            for event in self.file_events:
                self.multi_queue.put(event)
            self.mmc.touch_index_file()
            
            self.file_events = []

        #yield to worker thread
        time.sleep(0)
        
        #use items() because we are going to be modifying this
        #dictionary while iterating over it.
        for k, pair in self.cookies_IN_MOVED_FROM.items():
            event = pair[0]
            timestamp = pair[1]

            timestamp_now = time.time()

            if timestamp_now - timestamp > 5:
                #in_moved_from event didn't have a corresponding
                #in_moved_to event in the last 5 seconds.
                #This means the file was moved to outside of the
                #watched directories. Let's handle this by deleting
                #it from the Airtime directory.
                del self.cookies_IN_MOVED_FROM[k]
                self.handle_removed_file(False, event.pathname)
        
        # we don't want create_dict grow infinitely
        # this part is like a garbage collector
        for k, t in self.create_dict.items():
            now = time.time()
            if now - t > 5:
                # check if file exist
                # When whole directory is copied to the organized dir,
                # inotify doesn't fire IN_CLOSE_WRITE, hench we need special way of
                # handling those cases. We are manully calling handle_created_file
                # function.
                if os.path.exists(k):
                    # check if file is open                    
                    try:
                        command = "lsof "+k
                        #f = os.popen(command)
                        f = Popen(command, shell=True, stdout=PIPE).stdout
                    except Exception, e:
                        self.logger.error('Exception: %s', e)
                        self.logger.error("traceback: %s", traceback.format_exc())
                        continue
                    
                    if not f.readlines():
                        self.logger.info("Handling file: %s", k)
                        self.handle_created_file(False, k, os.path.basename(k))
                        del self.create_dict[k]
                else:
                        del self.create_dict[k]
开发者ID:vonloxx,项目名称:Airtime,代码行数:57,代码来源:airtimeprocessevent.py

示例12: fix_offsets

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import readlines [as 别名]
def fix_offsets():
    libc_printf_offset_cmd = Popen("gdb -batch -x offsets/libc_printf.gdb libc.so.6",	
				shell=True, stdout=PIPE, stderr=STDOUT, bufsize=1024).stdout
    libc_printf_offset_stdout = libc_printf_offset_cmd.readlines()

    libc_printf_offset = re.match("\$1 = {<text variable, no debug info>} (.*) <printf>\\n", 
            libc_printf_offset_stdout[0]).group(1)

    vuln_printf_offset_cmd = Popen("gdb -batch -x offsets/vuln_printf.gdb vuln",
				shell=True, stdout=PIPE, stderr=STDOUT, bufsize=1024).stdout
    vuln_printf_offset_stdout = vuln_printf_offset_cmd.readlines()
    vuln_printf_offset = re.match("\$1 = {<text variable, no debug info>} (.*) <printf>\\n", 
            vuln_printf_offset_stdout[3]).group(1)

    readelf_vuln_bss_cmd = Popen("readelf -S vuln | grep bss",
				shell=True, stdout=PIPE, stderr=STDOUT, bufsize=1024).stdout
    readelf_vuln_bss_stdout = readelf_vuln_bss_cmd.readlines()
    readelf_vuln_bss_addr = readelf_vuln_bss_stdout[0].split(' ')[27]

    return int(vuln_printf_offset, 16) - int(libc_printf_offset, 16), int(readelf_vuln_bss_addr, 16)
开发者ID:ChiChou,项目名称:rop-lang,代码行数:22,代码来源:helpers.py

示例13: main

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import readlines [as 别名]
def main(name):
   socket = generate_map(name)['networks']
   while True:
      pipe = Popen(['iwlist', 'wlan0', 'scan'], stdout = PIPE).stdout
      cells = parse_cells(pipe.readlines())
      for cell in cells:
         pair = [cell['Address'] + '_' + cell['Name'], int(cell['Signal'][0:-3])]
         print pair
         socket.send(dumps(pair))
      print 
      sleep(0.5)
开发者ID:erazor83,项目名称:PenguPilot,代码行数:13,代码来源:wifi_sensor.py

示例14: check_dmesg_for_ooops

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import readlines [as 别名]
def check_dmesg_for_ooops():
    ''' check for ooops in dmesg output '''
    oops_messages = ['BUG: unable to handle kernel paging request at',
                     'general protection fault']
    cmd_ = Popen('dmesg', shell=True, stdout=PIPE, close_fds=True).stdout
    for line in cmd_.readlines():
        if hasattr(line, 'decode'):
            line = line.decode()
        if any(mes in line for mes in oops_messages):
            return True
    return False
开发者ID:ddboline,项目名称:roku_app,代码行数:13,代码来源:roku_utils.py

示例15: call_svn_cmd

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import readlines [as 别名]
def call_svn_cmd(path, cmd, opts):
    """string, string, string -> string
    Call a svn command and return an xml string
    """
    stringlist = []
    cli_out = Popen("svn %s %s '%s' 2> /dev/null" % (cmd, opts, path), shell=True,
                    stdout=PIPE, close_fds=True).stdout
    try:
        stringlist = cli_out.readlines()
        xml_string = "".join(stringlist)
        return xml_string
    except:
        return None
开发者ID:bsmr-worldforge,项目名称:wombat,代码行数:15,代码来源:svn.py


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