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


Python Popen.pop方法代码示例

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


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

示例1: main

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import pop [as 别名]
def main():
	url = "https://www.virustotal.com/vtapi/v2/file/report"

	try:
		with open("setting.conf", "r") as log_file:
			source_path = log_file.readline().strip()
			destination_path = log_file.readline().strip()
			log_path = log_file.readline().strip()
			apikey = log_file.readline().strip()
	
		print "Your source path is "+source_path
		print "Your destination path is "+destination_path
		print "Your log path is "+log_path
		print "Your API key is "+apikey
	except:
		print "Usage: You need to make setting.conf first."
		print "In the file, you should put this content in order:"
		print "source path"
		print "destination path"
		print "log path"
		print "apikey"
		print "./get_mal_result.py"
		sys.exit(0)

	print "Now let's read from "+source_path
	try:
		flist = Popen(["/bin/ls",source_path],stdout=PIPE).stdout.read().split("\n")
		flist.pop()
	except:
		print "Fail to load the source path"
		print "Please check the path!"
		sys.exit(0)

	for fn in flist:
		md5 = os.path.splitext(fn)[0]
		if "_" in md5:
			md5 = md5[0:-2]
		jsonMD5 = destination_path+md5+".json"
		parameters = {"resource":md5,"apikey":apikey}
		
		try:
			print "It's "+md5+" turns."
			data = urllib.urlencode(parameters)
			req = urllib2.Request(url, data)
			response = urllib2.urlopen(req)
			jsonResult = response.read()
			print "Now writing data into "+jsonMD5
			with open(jsonMD5, 'w') as outfile:
				json.dump(jsonResult, outfile, sort_keys = True, indent = 4, ensure_ascii=False)
		except:
			print "Some problems happened with "+md5+"!"
			with open(log_path,"a") as file_handle:
				file_handle.write(md5+"\n")

		time.sleep(15)
开发者ID:evshary,项目名称:virustotal_asker,代码行数:57,代码来源:get_virustotal.py

示例2: available_images

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import pop [as 别名]
def available_images(request):
    running = is_running('/usr/local/bin/tklpatch-getimage') 
    if len(running) > 0:
        return HttpResponseRedirect('/baseimages/getimage/')
    if os.path.exists(settings.TKLPATCH_BASEIMAGES_FILE):
        imagelist = Popen(['tklpatch-getimage','--list'],stdout=PIPE).communicate()[0]
        imagelist = imagelist.split("\n")
        imagelist.pop() #Remove empty element
        baseimagelist = list_images()
        for x in baseimagelist:
            image = x[:-4]
            try:
                imagelist.remove(image)
            except:
                pass
    else:
        imagelist = ''
    return render_to_response('baseimages/listimages.html',{"imagelist": imagelist}, context_instance=RequestContext(request))
开发者ID:CompuTEK-Industries,项目名称:tkldevenv_webapp,代码行数:20,代码来源:views.py

示例3: df

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import pop [as 别名]
def df(cmd):
  data = {}
  r1 = re.compile('^/(dev/|)')

  output = Popen([cmd], stdout=PIPE, shell=True).communicate()[0].splitlines()

  output.pop(0)
  for line in output:
    fields = line.split()
    key = r1.sub('', fields[0]).replace('/', '_')
    data[key] = {
      'total': fields[1],
      'used': fields[2],
      'available': fields[3],
      'percent_used': fields[4].replace('-', '0').replace('%', ''),
      'mountpoint': fields[5]
    }

  return data
开发者ID:benjaminws,项目名称:porkchop-plugins,代码行数:21,代码来源:df.py

示例4: update_gunicorns

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import pop [as 别名]
def update_gunicorns(): 
    """
    Updates the dict of gunicorn processes. Run the ps command and parse its 
    output for processes named after gunicorn, building up a dict of gunicorn 
    processes. When new gunicorns are discovered, run the netstat command to 
    determine the ports they're serving on.
    """
    global tick
    tick += 1
    if (tick * screen_delay) % ps_delay != 0:
        return
    tick = 0
    for pid in gunicorns:
        gunicorns[pid].update({"workers": 0, "mem": 0})
    ps = Popen(PS_ARGS, stdout=PIPE).communicate()[0].split("\n")
    headings = ps.pop(0).split()
    name_col = headings.index("CMD")
    num_cols = len(headings) - 1
    for row in ps:
        cols = row.split(None, num_cols)
        if cols and cols[name_col].startswith("gunicorn: "):
            is_worker = cols[name_col].startswith("gunicorn: worker")
            if is_worker:
                pid = cols[headings.index("PPID")]
            else:
                pid = cols[headings.index("PID")]
            if pid not in gunicorns:
                gunicorns[pid] = {"workers": 0, "mem": 0, "port": None, "name": 
                    cols[name_col].strip().split("[",1)[1][:-1]}
            gunicorns[pid]["mem"] += int(cols[headings.index("RSS")])
            if is_worker:
                gunicorns[pid]["workers"] += 1
    # Remove gunicorns that were not found in the process list.
    for pid in gunicorns.keys()[:]:
        if gunicorns[pid]["workers"] == 0:
            del gunicorns[name]
    # Determine ports if any are missing.
    if not any([g for g in gunicorns.values() if g["port"] is None]):
        return
    netstat = Popen(["netstat","-lp"], stdout=PIPE, stderr=PIPE).communicate()[0].split("\n")
    addr_pos = None
    pid_pos = None
    addr_heading = "Local Address"
    pid_heading = "PID/Program name"
    for row in netstat :
        if addr_heading in row and pid_heading in row:
            addr_pos = row.index(addr_heading)
            pid_pos = row.index(pid_heading)
        if addr_pos is not None:
            pid = row[pid_pos:].split("/")[0]
            if pid in gunicorns:
                port = row[addr_pos:].split(" ", 1)[0].split(":")[1]
                gunicorns[pid]["port"] = port
开发者ID:benoitc,项目名称:gunicorn-console,代码行数:55,代码来源:gunicorn_console.py

示例5: get_data

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import pop [as 别名]
  def get_data(self):
    command = 'ss -tuna'
    data = self.gendict()

    output = Popen([command], stdout=PIPE, shell=True)\
                   .communicate()[0]\
                   .splitlines()

    output.pop(0)

    for line in output:
      fields = line.split()
      proto = fields[0]

      if proto == 'tcp':
        state = fields[1].lower()
        data[proto][state].setdefault('value', 0)
        data[proto][state]['value'] += 1
      else:
        data[proto].setdefault('value', 0)
        data[proto]['value'] += 1

    return dict(data)
开发者ID:benjaminws,项目名称:porkchop-plugins,代码行数:25,代码来源:tcpudp.py

示例6: preprocessFile

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import pop [as 别名]
def preprocessFile(filename):
    global CASource, protectedFunctions
    
    headerfile = filename.split('/')[-1][:-2]
    
    # Remove comments
    data = Popen(["gcc", "-fpreprocessed", "-dD", "-E", filename], stdout=PIPE).communicate()[0].splitlines(True)
    if not len(data):
        print("Error: Not a valid input file")
        sys.exit(0)
    
    # preprocessor comments
    data.remove(data[0])

    while('#include' in data[0]):
        CASource[0] += data.pop(0)
    CASource[0] += '\n#include "autogen_ca_header.h"\n\n'
    
    data[0] += "typedef struct aes_key_struct {\n\tint dummy;\n} AES_KEY;\ntypedef struct rsa_key_struct {\n\tint dummy;\n} RSA;\ntypedef unsigned long int uint32_t;\ntypedef unsigned long size_t;\n"

    # Search secure annotations
    for line in reversed(data):
        if '#pragma secure' in line:
            name = line.split()[-1]
            if ' function ' in line:
                protectedFunctions.append(FunctionObject(name))
            # Currently appends a name, not an object
            elif ' global ' in line:
                globalVariables.append(name)
            data.remove(line)
    
    for i in range(len(data)-1, -1, -1):
        if '#pragma shared var' in data[i]:
            funcIndex = i
            # Find name of the function
            while '#pragma shared var' in data[funcIndex]:
                funcIndex -= 1
            
            # Determine whether the function is marked as secure
            for func in protectedFunctions:
                if func.name in data[funcIndex]:
                    obj = ParameterObject(data[i].split()[-1], '', 1)
                    sharedVariables.append((func.name, obj))
        
        elif '#pragma shared header' in data[i]:
            TASource.append('\n#include "'+line.split()[-1]+'"\n')
    
    protectedFunctions = protectedFunctions[::-1]
    
    return ''.join(data)
开发者ID:ta-autogen,项目名称:ta-autogen,代码行数:52,代码来源:parser.py

示例7: update_gunicorns

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import pop [as 别名]
def update_gunicorns():
    """
    Updates the dict of gunicorn processes. Run the ps command and parse its
    output for processes named after gunicorn, building up a dict of gunicorn
    processes. When new gunicorns are discovered, run the netstat command to
    determine the ports they're serving on.
    """
    global tick
    tick += 1
    if (tick * screen_delay) % ps_delay != 0:
        return
    tick = 0
    for pid in gunicorns:
        gunicorns[pid].update({"workers": 0, "mem": 0})
    ps = Popen(PS_ARGS, stdout=PIPE).communicate()[0].split("\n")
    headings = ps.pop(0).split()
    name_col = headings.index(cmd_heading)
    num_cols = len(headings) - 1
    for row in ps:
        cols = row.split(None, num_cols)
        if cols and "gunicorn: " in cols[name_col]:
            if "gunicorn: worker" in cols[name_col]:
                is_worker = True
            else:
                is_worker = False

            if is_worker:
                pid = cols[headings.index("PPID")]
            else:
                pid = cols[headings.index("PID")]
            if pid not in gunicorns:
                gunicorns[pid] = {"workers": 0, "mem": 0, "port": None, "name":
                    cols[name_col].strip().split("[",1)[1].split("]",1)[:-1]}
            gunicorns[pid]["mem"] += int(cols[headings.index("RSS")])
            if is_worker:
                gunicorns[pid]["workers"] += 1
    # Remove gunicorns that were not found in the process list.
    for pid in gunicorns.keys()[:]:
        if gunicorns[pid]["workers"] == 0:
            del gunicorns[pid]
    # Determine ports if any are missing.
    if not [g for g in gunicorns.values() if g["port"] is None]:
        return
    for (pid, port) in ports_for_pids(gunicorns.keys()):
        if pid in gunicorns:
            gunicorns[pid]["port"] = port
开发者ID:Mondego,项目名称:pyreco,代码行数:48,代码来源:allPythonContent.py

示例8: Popen

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import pop [as 别名]
# -*- coding: iso-8859-15 -*-

from sys import argv
from subprocess import Popen, PIPE
from shlex import split
from mailer import MailTransport, Email


# list files

files = Popen(split('find "'+argv[1]+'" -name "*.exe"'), stdout=PIPE).communicate()[0].strip()
open('exe.list','w').write(files)
files = files.split('\n')
for i in range(len(files)):
	if files[i] == '':
		files.pop(i)

# scan two files at once

def scan(filename):
	return Popen(split('clamscan --infected --no-summary "'+filename+'"'), stdout=PIPE)

def sendmail(log):
	Email(From='Kafka <[email protected]>', To='[email protected]', Subject='clamscan @ Kafka: FOUND', Text=log).send( MailTransport(Account='[email protected]') )

log = ''
found = False
while len(files) > 0:
	p1 = scan(files.pop())
	p2 = None
	if len(files) > 0:
开发者ID:carpediemberlin,项目名称:CaDiBackup,代码行数:33,代码来源:scan.py

示例9: exonerate

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import pop [as 别名]
 def exonerate(self,qryfas, genome, model,exonerate='exonerate',bestn=0):
     '''
     Runs exonerate and parses output into lists for processing.
     { query: {'gff':[outputlines], 'cigar':[outputlines], 'alignment':[outputlines], 'vulgar':[[headerlist], {header:value}, {header:value}, ...] }
     '''
     try:### ~ [1] Setup ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ###
         EXFILE = None
         exfile = '%s.%s' % (self.baseFile(),model)  # Used in memsaver mode
         query_dic = {}
         header_list = ['query_id', 'query_start', 'query_end', 'query_strand', 'target_id', 'target_start', 'target_end', 'target_strand', 'score', '<label, query_length, target_length> triplets']
         excmd = [exonerate, qryfas, genome, '--showtargetgff', '--showcigar']
         if model: excmd += ['--model', model]
         if bestn: excmd += ['--bestn', '%d' % bestn]
         if self.getStrLC('ExOpt'): excmd += string.split(self.getStr('ExOpt'))
         self.printLog('#RUN',string.join(excmd))
         extext = []
         if self.getBool('MemSaver'):
             gzfile = '%s.gz' % exfile
             if rje.exists(gzfile): self.gUnzip(gzfile)
             if rje.exists(exfile) and not self.force():
                 self.printLog('#EXFILE','Found %s (force=F). Assuming complete.' % exfile)
             else:
                 rje.backup(self,exfile)
                 self.printLog('#SAVER','memsaver=T: Exonerate output directed to %s.' % exfile)
                 EXFILE = open(exfile,'w')
                 if subprocess.call(excmd, stdout=EXFILE): raise IOError('Exonerate call did not complete!')
                 EXFILE.close()
                 self.printLog('#EXFILE','%s generated.' % exfile)
             EXFILE = open(exfile,'r')
         else:
             extext = Popen(excmd, stdout=PIPE).stdout.readlines()
         output_format = ''
         while extext or EXFILE:
             #line = process.stdout.readline().rstrip()
             if EXFILE:
                 line = EXFILE.readline()
                 if not line: break
                 line = rje.chomp(line)
             else: line = rje.chomp(extext.pop(0))
             if line:
                 if line.startswith('         Query:'):
                     query = line.split(':', 1)[1].split(' ')[1]
                     #for q in rje.sortKeys(query_dic):
                     #    self.bugPrint('%s: %s' % (q,rje.sortKeys(query_dic[q])))
                     #self.debug(query)
                 if line == 'C4 Alignment:':
                     output_format = 'alignment'
                 elif line == '# --- START OF GFF DUMP ---':
                     output_format = 'gff'
                 elif line.startswith('vulgar:'):
                     output_format = 'vulgar'
                     fields = line.split(' ', 10)[1:]
                     if output_format in query_dic[query]:
                         query_dic[query][output_format].append({})
                     else:
                         query_dic[query][output_format] = [header_list, {}]
                     for header, field in zip(header_list, fields):
                         query_dic[query][output_format][-1][header] = field
                     #self.debug(query_dic[query][output_format])
                 elif line.startswith('cigar:'):
                     output_format = 'cigar'
                     if output_format in query_dic[query]:
                         query_dic[query][output_format].append(line.replace('cigar: ', ''))
                     else:
                         query_dic[query][output_format] = [line.replace('cigar: ', '')]
                 elif line == '------------' or line.startswith('Command line:') or line.startswith('Hostname:') or line == '# --- END OF GFF DUMP ---' or line == '#' or line.startswith('-- completed exonerate analysis'):
                     pass
                 elif output_format:
                     if query in query_dic:
                         if output_format in query_dic[query]:
                             query_dic[query][output_format].append(line)
                         else:
                             query_dic[query][output_format] = [line]
                     else:
                         query_dic[query] = {output_format:[line]}
             #elif process.poll() is not None:
             #    break
             elif output_format == 'alignment':
                 try: query_dic[query][output_format].append(line)
                 except: pass
             self.vPrint(line,v=1)
         if EXFILE:
             EXFILE.close()
             if self.getBool('Cleanup'):
                 os.unlink(exfile)
                 self.printLog('#CLEAN','%s deleted.' % exfile)
             elif self.getBool('GZip'): self.gZip(exfile)
         return query_dic
     except: self.errorLog('%s.exonerate error' % self.prog()); raise
开发者ID:slimsuite,项目名称:SLiMSuite,代码行数:91,代码来源:rje_exonerate.py


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