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


Python Popen.splitlines方法代码示例

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


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

示例1: start_match

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import splitlines [as 别名]
def start_match(team1, team2):
    """Start a match between team1 and team2. Return which team won (1 or 2) or
    0 if there was a draw.
    """
    global rnames
    print
    print rnames[team1], "vs", rnames[team2]
    print
    args = CMD_STUB.split()
    args.extend([team1, team2])
    print "Starting", " ".join(args)
    stdout, stderr = Popen(args, stdout=PIPE, stderr=PIPE).communicate()
    tmp = reversed(stdout.splitlines())
    lastline = None
    # get the real names of the teams.
    # pelitagame will output two lines of the following form:
    # Using factory 'RandomPlayer' -> 'The RandomPlayers'
    for line in stdout.splitlines():
        if line.startswith("Using factory '"):
            split = line.split("'")
            tname, rname = split[1], split[3]
            rnames[tname] = rname
    for line in tmp:
        if line.startswith("Finished."):
            lastline = line
            break
    if not lastline:
        print "*** ERROR: Apparently the game crashed. At least I could not find the outcome of the game."
        print "*** Maybe stderr helps you to debug the problem"
        print stderr
        print "***"
        return 0
    print "***", lastline
    if lastline.find("had a draw.") >= 0:
        print "Draw!"
        return 0
    else:
        tmp = lastline.split("'")
        winner = tmp[1]
        loser = tmp[3]
        if winner == rnames[team1]:
            print team1, "wins."
            return 1
        elif winner == rnames[team2]:
            print team2, "wins."
            return 2
        else:
            print "Unable to parse winning result :("
            return 0
开发者ID:pv,项目名称:pelita,代码行数:51,代码来源:tournament.py

示例2: test_rename_combo

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import splitlines [as 别名]
def test_rename_combo():    
    comm = "vk rename --prefix PREFIX_ --suffix _SUFFIX --subst N2:TEST --subst WN2001,TEST2 --subst AB1=TEST3 test_data/test.vcf.gz | bcftools query --list-samples"
    rename.main(["rename","--prefix","PREFIX_","--suffix","_SUFFIX","--subst","N2:TEST","--subst","WN2001,TEST2","--subst","AB1=TEST3","test_data/test.vcf.gz"])
    out, err = Popen(comm, stdout=PIPE, stderr=PIPE, shell=True).communicate()
    assert all([x.startswith("PREFIX_") for x in out.splitlines()])
    assert sum(["TEST" in x for x in out.splitlines()]) == 3
    assert all([x.endswith("_SUFFIX") for x in out.splitlines()])
开发者ID:AndersenLab,项目名称:vcf-kit,代码行数:9,代码来源:test_rename.py

示例3: main

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import splitlines [as 别名]
def main():
    branch = is_repo()

    res, err = Popen(['git','diff','--name-status'], stdout=PIPE, stderr=PIPE).communicate()
    err_string = err.decode('utf-8')
    if 'fatal' in err_string:
        sys.exit(0)
    changed_files = [namestat[0] for namestat in res.splitlines()]
    staged_files = [namestat[0] for namestat in Popen(['git','diff', '--staged','--name-status'], stdout=PIPE).communicate()[0].splitlines()]
    nb_changed = len(changed_files) - changed_files.count('U')
    nb_U = staged_files.count('U')
    nb_staged = len(staged_files) - nb_U
    staged = str(nb_staged)
    conflicts = str(nb_U)
    changed = str(nb_changed)
    nb_untracked = len(Popen(['git','ls-files','--others','--exclude-standard'],stdout=PIPE).communicate()[0].splitlines())
    untracked = str(nb_untracked)
    if not nb_changed and not nb_staged and not nb_U and not nb_untracked:
        clean = '1'
    else:
        clean = '0'

    remote = ''

    if not branch: # not on any branch
        branch = symbols['prehash']+ Popen(['git','rev-parse','--short','HEAD'], stdout=PIPE).communicate()[0][:-1]
    else:
        remote_name = Popen(['git','config','branch.%s.remote' % branch], stdout=PIPE).communicate()[0].strip()
        if remote_name:
            merge_name = Popen(['git','config','branch.%s.merge' % branch], stdout=PIPE).communicate()[0].strip()
            if remote_name == '.': # local
                remote_ref = merge_name
            else:
                remote_ref = 'refs/remotes/%s/%s' % (remote_name, merge_name[11:])
            revgit = Popen(['git', 'rev-list', '--left-right', '%s...HEAD' % remote_ref],stdout=PIPE, stderr=PIPE)
            revlist = revgit.communicate()[0]
            if revgit.poll(): # fallback to local
                revlist = Popen(['git', 'rev-list', '--left-right', '%s...HEAD' % merge_name],stdout=PIPE, stderr=PIPE).communicate()[0]
            behead = revlist.splitlines()
            ahead = len([x for x in behead if x[0]=='>'])
            behind = len(behead) - ahead
            if behind:
                remote += '%s%s' % (symbols['behind'], behind)
            if ahead:
                remote += '%s%s' % (symbols['ahead of'], ahead)

    out = '\n'.join([
        branch,
        remote,
        staged,
        conflicts,
        changed,
        untracked,
        clean])
    print(out)
开发者ID:rfrohl,项目名称:dotfiles,代码行数:57,代码来源:gitstatus.py

示例4: disk_usage

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import splitlines [as 别名]
def disk_usage(path):
    """Return disk usage statistics about the given path."""    	
    output = Popen(['df', '-k', path], stdout=PIPE).communicate()[0]
    try:
        df = output.splitlines()[2].split()
        device = output.splitlines()[1]
        (size, used, free, percent, mountpoint) = df
    except IndexError:
        df = output.splitlines()[1].split()
        (device, size, used, free, percent, mountpoint) = df
    return (device, int(size), int(used), int(free), percent, mountpoint)
开发者ID:cgoldberg,项目名称:linux-metrics,代码行数:13,代码来源:disk_stat.py

示例5: updatevalues

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import splitlines [as 别名]
	def updatevalues(self):
		variable = Popen("sensors -A", stdout=PIPE, shell=True).stdout.read()
		splitvar = variable.splitlines()
		if variable == "":
			print("no sensors")
			return False
		self.titlelist = []
		self.fanarray = {}
		self.temperaturearray = {}
		for x in range(0, len(splitvar)):
			if not(splitvar[x] == ""):
				#sensors output means only titles lack a colon
				if (splitvar[x].find(':') == -1): 
					self.titlelist.append(splitvar[x])
					currentsection = splitvar[x]
				#find all the fan lines
				elif not(splitvar[x].find('fan') == -1):
					splitline = splitvar[x].split()
					data = [(currentsection, splitline[0], splitline[1])]
					for busdevice, sensor, value in data:
						self.fanarray.setdefault(busdevice, {})[sensor] = value
				#find all the lines with a degree sign in
				elif not(splitvar[x].find('\xc2') == -1):
					splitline = splitvar[x].split(':')
					data = [(currentsection,splitline[0],splitline[1].split()[0])]
					for busdevice, sensor, value in data:
						self.temperaturearray.setdefault(busdevice, {})[sensor] = value
开发者ID:MM294,项目名称:psensors,代码行数:29,代码来源:sensors.py

示例6: dosetup

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import splitlines [as 别名]
def dosetup(**kwargs):
    if 'enabled' not in kwargs:
	kwargs['enabled'] = False

    kwargs['server']=kwargs['server'][:-1] # take out extra /
    for set in ['hash_id', 'server', 'password', 'enabled',
		'cron_minute', 'cron_hour', 'cron_dom', 'cron_month', 'cron_dow']:
	setSetting(set, kwargs[set])

    old_crontab=Popen(['crontab', '-l'], stdout=PIPE).communicate()[0]
    print old_crontab

    filename = tempfile.mkstemp('crontab')[1]
    new_crontab=file(filename, 'w')
    for line in old_crontab.splitlines():
	if line.find('pushrecords')==-1:
	    new_crontab.write('%s\n' % line)

    if kwargs['enabled']:
	line = '%(cron_minute)s %(cron_hour)s %(cron_dom)s %(cron_month)s %(cron_dow)s' % kwargs
	line = '%s cd /opt/openproximity2; /bin/bash manager.sh egg_command pushrecords >> /tmp/pushrecords.log' % line
	new_crontab.write('%s\n' % line)
    new_crontab.close()

    call(['crontab', filename])
    print Popen(['crontab', '-l'], stdout=PIPE).communicate()[0]
    os.unlink(filename)
开发者ID:OpenProximity,项目名称:plugins-agent2,代码行数:29,代码来源:views.py

示例7: diff

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import splitlines [as 别名]
def diff(old,new):
    """
        Do a diff of two src trees, parse out file names, returns a dict
        with lists
        { new: [...], differ: [...], removed: [...] }
    """
        #do a diff of old and new
    cmd = 'LC_ALL=C diff -rq %s %s | grep -v .svn' % (old,new)    
    res = Popen(cmd,shell=True,stdout=PIPE).communicate()[0]

    differ  = []
    new     = []
    removed = []
    for l in res.splitlines():
        if l.endswith('differ'):
            differ.append(l.split()[3])
        elif l.startswith('Only'):
            s = l.split()
            fpth = path.join(s[2][:-1],s[3])

            if 'alfresco-enterprise-3.4.4' in l:
                new.append(fpth)
            else:
                removed.append(fpth)
                
    return { 'differ': differ, 'removed':removed, 'new':new }
开发者ID:Redpill-Linpro,项目名称:Alfresco-Tooling,代码行数:28,代码来源:migrate_diff.py

示例8: __queueCheck

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import splitlines [as 别名]
    def __queueCheck (self):
        """This method runs over each hop in a route and checks the latency 
        of all hops"""
        
        print "Going for a quick run using one packetsize, to check the queue delay"
        
        roundTimeStamp = time.time()

        for packetCount in range (self.maxHopReps):
            sleep (0.5)
            for hop in range (1,self.hopsRequired+1):
                output = Popen (["traceroute", "-n", "-q", "1", "-T", "-f", str (hop), "-m", str (hop), self.targetHost, "1042"], stdout=PIPE).communicate()[0]
                print output

                for line in output.splitlines()[1:]:
                    
                    traceroute = line.split()
                    self.packetsSent += 1
                    # If the packet timed out
                    if len (traceroute) < 3:
                        self.packetsLost += 1
                        continue

                    # interperating the stuff we got back from traceroute
                    tracerouteHop = traceroute[0].strip() 
                    tracerouteIP  = traceroute[1].strip().lstrip("(").rstrip(")")
                    tracerouteRTT = traceroute[2].strip() # this is still a string, not a float
                    
                    tracerouteRTT = float (tracerouteRTT) / 1000.0        
                    self.resultset.add (tracerouteHop, 1098, tracerouteRTT, roundTimeStamp)
        
        print "Queuecheck done"
        print "Send {0} packets, lost {1}".format(self.packetsSent,self.packetsLost)
开发者ID:dtaht,项目名称:Buffchar,代码行数:35,代码来源:Prober.py

示例9: test_flake8

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import splitlines [as 别名]
    def test_flake8(self):
        """Test if the code is Flake8 compliant."""
        if os.environ.get('ON_TRAVIS', False):
            root = '../'
            command = ['flake8']
            output = Popen(command, stdout=PIPE, cwd=root).communicate()[0]
            default_number_lines = 0
        elif sys.platform.startswith('win'):
            # ET I don't know on windows.
            pass

        else:
            # OSX and linux just delegate to make
            root = '../../'
            command = ['make', 'flake8']
            output = Popen(command, stdout=PIPE, cwd=root).communicate()[0]
            default_number_lines = 0

        # make pep8 produces some extra lines by default.
        lines = len(output.splitlines()) - default_number_lines
        print output
        message = (
            'Hey mate, go back to your keyboard :) (expected %s, got %s '
            'lines from PEP8.)' % (default_number_lines, lines))
        self.assertEquals(lines, 0, message)
开发者ID:Christiaanvdm,项目名称:ford3,代码行数:27,代码来源:test_python_style.py

示例10: _generate_mountpoint_topology

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import splitlines [as 别名]
	def _generate_mountpoint_topology(cls):
		"""
		Gets the information about disks, partitions and mountpoints. Stores information about used filesystem and
		creates a list of all underlying devices (in case of LVM) for each mountpoint.
		"""
		mountpoint_topology = {}
		current_disk = None

		stdout, stderr = Popen(["/usr/bin/lsblk", "-rno", "TYPE,RM,KNAME,FSTYPE,MOUNTPOINT"], stdout=PIPE, stderr=PIPE, close_fds=True).communicate()
		for columns in map(lambda line: line.split(), stdout.splitlines()):
			if len(columns) < 3:
				continue
			device_type, device_removable, device_name = columns[:3]
			filesystem = columns[3] if len(columns) > 3 else None
			mountpoint = columns[4] if len(columns) > 4 else None

			if device_type == "disk":
				current_disk = device_name
				continue

			# skip removable, skip nonpartitions
			if device_removable == "1" or device_type not in ["part", "lvm"]:
				continue

			if mountpoint is None or mountpoint == "[SWAP]":
				continue

			mountpoint_topology.setdefault(mountpoint, {"disks": set(), "device_name": device_name, "filesystem": filesystem})
			mountpoint_topology[mountpoint]["disks"].add(current_disk)

		cls._mountpoint_topology = mountpoint_topology
开发者ID:adamBrinek,项目名称:tuned,代码行数:33,代码来源:plugin_mounts.py

示例11: add_new_apps

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import splitlines [as 别名]
def add_new_apps(apps):
    """ Add new applications to apps' dict
    """
    curr_apps = Popen(DMENU_PATH, stdout=PIPE).communicate()[0]
    for app in curr_apps.splitlines():
        apps.setdefault(app, 0)
    return apps
开发者ID:sorrat,项目名称:dotfiles,代码行数:9,代码来源:pydmenu.py

示例12: __init__

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import splitlines [as 别名]
 def __init__(self):
     self.logger = logging.getLogger(__name__)
     self.logger.debug('Initializing notify object')
     if sys.platform == 'linux2':
         self.user = ''
         who = Popen(['/usr/bin/who'], stdout=PIPE).stdout.read()
         for line in who.splitlines():
             if 'tty7' in line:
                 self.user = line.split()[0]  
                 if '(' in line.split()[-1]:
                     self.display = line.split()[-1].replace('(','').replace(')','')
                 else:
                     self.display = ':0'
                 break
         if not self.user:
             self.logger.error('User not found in tty7. Probably no one logged in or in other terminal') 
             raise Exception('No user found.')              
         self.logger.debug('Set user : {0}'.format(self.user))
         self.logger.debug('Set display : {0}'.format(self.display))
         self.logger.debug('Initializing pynotify')
         pynotify.init('Summary')
         self.__notifier = pynotify.Notification
         self.message = self.__message
                    
     if sys.platform == 'win32':
         self.logger.debug('Initializing WindowsBalloonTip')
         self.__notifier = WindowsBalloonTip()
         self.message = self.__message
开发者ID:costastf,项目名称:blind-Pyrsync,代码行数:30,代码来源:notify.py

示例13: monitor

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import splitlines [as 别名]
def monitor(p):
    def cputimestring2secs(str):
        m = cputime_RE.match(str)

        secs = 60 * int(m.group(2)) + float(m.group(3))
        if m.group(1) is not None:
            secs += 3600 * int(m.group(1))

        return secs

    rsz = vsz = cpu = -1
    while p.poll() is None:
        try:
            r = Popen(("ps", "-p", str(p.pid), "-o" "rsz,vsz,cputime"),
                      stdout=PIPE,
                      env=os.environ).communicate()[0]

            ps = r.splitlines()[1].split()
            rsz = max(rsz, int(ps[0]) * 1024)
            vsz = max(vsz, int(ps[1]) * 1024)
            cpu = max(cpu, cputimestring2secs(ps[2]))
        except:
            break

    return rsz, vsz, cpu
开发者ID:usnistgov,项目名称:fipy,代码行数:27,代码来源:benchmarker.py

示例14: main

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import splitlines [as 别名]
def main():
    args = parse_args()
    redis_info = Popen(('redis-cli', '-a', redis_pwd(), 'info'),
                       stdout=PIPE).stdout.read()
    redis_info = redis_info.splitlines()

    redis_stats = {}
    for x in redis_info:
        if x.find(':') != -1:
            key, value = x.split(':')
            redis_stats[key] = value

    template = args.prefix + '.{} {} ' + str(int(time()))
    headers = (
        'total_connections_received',
        'total_commands_processed',
        'keyspace_hits',
        'keyspace_misses',
        'used_memory',
        'used_cpu_sys',
        'used_cpu_user',
        'used_cpu_sys_children',
        'used_cpu_user_children',
    )
    for metric in headers:
        print(template.format(metric, redis_stats[metric]))
开发者ID:Phantuman,项目名称:igcollect,代码行数:28,代码来源:redis.py

示例15: runcmd

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import splitlines [as 别名]
def runcmd(cmd, *args):
    "helper function to grab output of a shell command."
    if args:
        cmd = cmd + ' ' + ' '.join(args)

    output = Popen(shlex.split(cmd), stdout=PIPE).communicate()[0]
    return output.splitlines()
开发者ID:thebjorn,项目名称:dkcoverage,代码行数:9,代码来源:shell.py


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