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


Python Popen.replace方法代码示例

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


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

示例1: encrypt

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import replace [as 别名]
def encrypt(text):
    encryption_password = weechat.config_get_plugin("encryption_password")

    # decrypt the password if it is stored as secured data
    if encryption_password.startswith("${sec."):
        encryption_password = weechat.string_eval_expression(encryption_password, {}, {}, {})

    if PY3:
        text = text.encode("UTF-8")

    command="openssl enc -aes-128-cbc -salt -base64 -md md5 -A -pass env:OpenSSLEncPW"
    opensslenv = os.environ.copy();
    # Unknown whether the encryption password should or should not be
    # (UTF8-)encoded before being passed to the environment in python 3.
    opensslenv['OpenSSLEncPW'] = encryption_password
    output, errors = Popen(shlex.split(command), stdin=PIPE, stdout=PIPE,
                           stderr=PIPE,env=opensslenv).communicate(text + b" ")
    output = output.replace(b"/", b"_")
    output = output.replace(b"+", b"-")
    output = output.replace(b"=", b"")

    if PY3:
        output = output.decode("UTF-8")

    return output
开发者ID:oakkitten,项目名称:scripts,代码行数:27,代码来源:irssinotifier.py

示例2: get_source_dir

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import replace [as 别名]
 def get_source_dir(self):
     sourcedir= Popen(["rpm", "-E", '%_sourcedir' ], stdout=subprocess.PIPE).stdout.read()[:-1]
     # replace %{name} by the specname
     package_name = Popen(["rpm", "-qp", self.filename, '--qf', '%{name}' ], stdout=subprocess.PIPE).stdout.read()
     sourcedir = sourcedir.replace("%{name}", package_name)
     sourcedir = sourcedir.replace("%name", package_name)
     return sourcedir
开发者ID:fabaff,项目名称:FedoraReview,代码行数:9,代码来源:__init__.py

示例3: launch

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import replace [as 别名]
 def launch(app, mon, in_new_wks):
     if '-cd' in app:
         xcwd = Popen('xcwd', stdin=PIPE, stdout=PIPE).communicate()[0]
         # TODO: replace all possible special characters
         xcwd = xcwd.replace('\n', '')
         special_chars = [' ', '(', ')']
         for c in special_chars:
             xcwd = xcwd.replace(c, r'\{0}'.format(c))
         app = '"' + app + ' ' + xcwd + '"'
     if not in_new_wks and (
             mon == 'all' or
             mon == utils.get_current_output()):
         # open on the current workspace
         a = action.Action()
         a.add(action.Action.exec_, (app,))
         action.default_mode(a)
         i3.subscribe('window', 'new',
                      utils.set_window_mark_callback,
                      lambda: a.process())
     if not in_new_wks and (
             mon != 'all' and
             mon != utils.get_current_output()):
         # open on the visible workspace on another output
         otherw = utils.get_current_workspace(mon)
         a = action.Action()
         a.add(action.Action.jump_to_workspace, (otherw,))
         a.add(action.Action.exec_, (app,))
         action.default_mode(a)
         i3.subscribe('window', 'new',
                      utils.set_window_mark_callback,
                      lambda: a.process())
     elif in_new_wks and (
             mon == 'all' or
             mon == utils.get_current_output()):
         # new workspace on the current output
         neww = utils.get_free_workspaces()[0]
         a = action.Action()
         a.add(action.Action.jump_to_workspace, (neww,))
         a.add(action.Action.exec_, (app,))
         action.default_mode(a)
         i3.subscribe('window', 'new',
                      utils.set_window_mark_callback,
                      lambda: a.process())
     elif in_new_wks and (
             mon != 'all' and
             mon != utils.get_current_output()):
         # new workspace on another output
         neww = utils.get_free_workspaces()[0]
         a = action.Action()
         a.add(action.Action.focus_output, (mon,))
         a.add(action.Action.jump_to_workspace, (neww,))
         a.add(action.Action.exec_, (app,))
         action.default_mode(a)
         i3.subscribe('window', 'new',
                      utils.set_window_mark_callback,
                      lambda: a.process())
开发者ID:syl20bnr,项目名称:i3ci,代码行数:58,代码来源:__init__.py

示例4: get_fortune

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import replace [as 别名]
def get_fortune(request):

    msg = ""
    while not msg:
        # Avoid empty messages that are returned sometimes ...
        msg = Popen([settings.FORTUNE_BIN, settings.FORTUNE_PATH], stdout=PIPE).communicate()[0]

    #FIXME: to be split and passed to template as context
    msg = '<div class="italic">' + msg
    msg = msg.replace("-- ", '</div><div class="author">')
    msg += '</div>'
    msg = msg.replace("\n","<br />")
    return HttpResponse(msg)
开发者ID:feroda,项目名称:JAGOM,代码行数:15,代码来源:views.py

示例5: rename_file

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import replace [as 别名]
def rename_file (video_file_name_extn, extn):

    # Extract the meta data into a temporary file "meta.txt"
    Popen ('ffmpeg -i \"' + video_file_name_extn + '\" -f ffmetadata ' + ' meta.txt' , shell=True, stdout=PIPE).stdout.read()

    # Extract the show name
    show_name = Popen ('grep show= meta.txt' , shell=True, stdout=PIPE).stdout.read()
    
    # Do not rename if it is not a show
    if (show_name == ''):
        system ('rm -rf meta.txt')
        return (video_file_name_extn)
    show_name = show_name.replace ('show=', '')
    show_name = show_name.rstrip()

    # Extract the season number
    season = Popen ('grep season_number meta.txt' , shell=True, stdout=PIPE).stdout.read()
    season = season.replace ('season_number=', '')
    season = season.rstrip()

    # Extract the episode number
    episode_sort = Popen ('grep episode_sort meta.txt' , shell=True, stdout=PIPE).stdout.read()
    episode_sort = episode_sort.replace ('episode_sort=', '')
    episode_sort = episode_sort.rstrip()

    # Extract the episode title
    episode_name = Popen ('grep title= meta.txt' , shell=True, stdout=PIPE).stdout.read()
    episode_name = episode_name.replace ('title=', '')
    episode_name = episode_name.rstrip()
    
    # Delete temporary "meta.txt" file.
    system ('rm -rf meta.txt')

    # Construct the complete file name
    final_episode_name = ''
    if (int(season)<10):
        final_episode_name = final_episode_name + show_name + ' S0' + season
    else:
        final_episode_name = final_episode_name + show_name + ' S'  + season


    if (int(episode_sort) < 10):
        final_episode_name = final_episode_name + 'E0' + episode_sort
    else:
        final_episode_name = final_episode_name + 'E' + episode_sort

    final_episode_name = final_episode_name + ' ' + episode_name + extn

    # Return the constructed file name
    return final_episode_name
开发者ID:avdd80,项目名称:rename,代码行数:52,代码来源:rename.py

示例6: _convertToHTML

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import replace [as 别名]
  def _convertToHTML(self):
    """
    Convert the PDF text content to HTML with pdftohtml

    NOTE: XXX check that command exists and was executed
    successfully
    """
    if not self.hasData():
      return ''
    tmp = tempfile.NamedTemporaryFile()
    tmp.write(self.getData())
    tmp.seek(0)

    command_result = None
    try:
      command = ['pdftohtml', '-enc', 'UTF-8', '-stdout',
                 '-noframes', '-i', tmp.name]
      try:
        command_result = Popen(command, stdout=PIPE).communicate()[0]
      except OSError, e:
        if e.errno == errno.ENOENT:
          raise ConversionError('pdftohtml was not found')
        raise

    finally:
      tmp.close()
    # Quick hack to remove bg color - XXX
    h = command_result.replace('<BODY bgcolor="#A0A0A0"', '<BODY ')
    # Make links relative
    h = h.replace('href="%s.html' % tmp.name.split(os.sep)[-1],
                                                          'href="asEntireHTML')
    return h
开发者ID:Provab-Solutions,项目名称:erp5,代码行数:34,代码来源:PDFDocument.py

示例7: testUnoConverterOdtToDoc

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import replace [as 别名]
 def testUnoConverterOdtToDoc(self):
   """Test script unoconverter"""
   mimemapper = dict(filter_list=[('doc',
                                   'com.sun.star.text.TextDocument',
                                   'MS Word 97')],
                    doc_type_list_by_extension=dict(doc=['com.sun.star.text.TextDocument']))
   mimemapper_pickled = json.dumps(mimemapper)
   python = join(self.office_binary_path, "python")
   command = [exists(python) and python or "python",
         pkg_resources.resource_filename("cloudooo.handler.ooo",
                                         "/helper/unoconverter.py"),
         "--convert",
         "--uno_path=%s" % self.uno_path,
         "--office_binary_path=%s" % self.office_binary_path,
         "--hostname=%s" % self.hostname,
         "--port=%s" % self.port,
         "--document_url=%s" % self.document.getUrl(),
         "--destination_format=%s" % "doc",
         "--source_format=%s" % "odt",
         "--mimemapper=%s" % mimemapper_pickled]
   stdout, stderr = Popen(command,
                          stdout=PIPE,
                          stderr=PIPE).communicate()
   self.assertEquals(stderr, '')
   output_url = stdout.replace('\n', '')
   self.assertTrue(exists(output_url), stdout)
   mime = magic.Magic(mime=True)
   self.assertEquals(mime.from_file(output_url), 'application/msword')
   self.document.trash()
   self.assertEquals(exists(output_url), False)
开发者ID:Seb182,项目名称:cloudooo,代码行数:32,代码来源:testOooUnoConverter.py

示例8: find_cal_mwats

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import replace [as 别名]
def find_cal_mwats(obs_id):
    obs_id = obs_id.split('\n')[0]
    obs_id = obs_id.strip()
    date_output = Popen(["python", "/short/ek6/MWA_Code/bin/get_observation_info.py", "-g", str(obs_id)], stdout=PIPE).communicate()[0]
    date_output = date_output.split()[7]
    date_output = date_output.replace('/', '-')
    date_output = date_output[1:11]
    print "Observation date "+date_output
    os.chdir('/short/ek6/CALS/')
    cal_list = open('MWATS_cal_list.txt', 'r')
    return_cal = None
    for line in cal_list:
        sdate  = line.split(',')[0]
        cal_id = line.split(',')[1]
        cal_id = cal_id.split(' ')[1]
        if sdate == date_output:
           print 'Recomended calibrator is '+cal_id
           for cal in glob.glob('*.cal'):
               cal_num = cal[0:10]
               if cal_id.split('\n')[0] == cal_num:
                  print "Found calibration file "+cal
                  return_cal = '/short/ek6/CALS/'+cal
    if return_cal == None:
           print "No calibrator file found, please generate it"
    return return_cal
开发者ID:mebell,项目名称:MWA_SIP,代码行数:27,代码来源:get_data.py

示例9: backup_database

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import replace [as 别名]
def backup_database(request):

    if request.method == 'POST':

        output = Popen(['which', 'mysqldump'], stdout=PIPE, close_fds=True).communicate()[0]

        mysqldump_bin = output.replace('\n','')

        cmd = mysqldump_bin+' -h %s --opt --compact --skip-add-locks -u %s -p%s %s' % \
                    (getattr(settings.DATABASES['default'], 'HOST', 'localhost'),
                     settings.DATABASES['default']['USER'],
                     settings.DATABASES['default']['PASSWORD'],
                     settings.DATABASES['default']['NAME'])

        pop1 = Popen(cmd.split(" "), stdout=PIPE, close_fds=True)
        pop2 = Popen(["bzip2", "-c"], stdin=pop1.stdout, stdout=PIPE, close_fds=True)
        output = pop2.communicate()[0]
        
        default_storage.save(BACKUP_DIR+"/"+datetime.today().strftime("%Y-%m-%d_%H:%M:%S")+"_db.sql.bz2", ContentFile(output))
    
    files = default_storage.listdir(BACKUP_DIR)[1]
    files.sort(reverse=True)
    return render_to_response('diagnostic/backupdb.html', 
                                {'files':files,}, 
                                context_instance=RequestContext(request))
开发者ID:AnaBiel,项目名称:opentrials,代码行数:27,代码来源:views.py

示例10: __launch_desktop_blocker

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import replace [as 别名]
    def __launch_desktop_blocker(self, session_name, user_id, x11_display):
        print "Launch desktop-blocker to '%s'" % session_name
        from os import environ 
        env = environ.copy()
        env["DISPLAY"] = x11_display

        proclist = gtop.proclist(gtop.PROCLIST_KERN_PROC_UID, int(user_id))

        if len(proclist) > 0 :
            from subprocess import Popen, PIPE
            lang_var = Popen('cat /proc/%s/environ | tr "\\000" "\\n" | grep ^LANG= ' % proclist[0] , shell=True, stdout=PIPE).stdout.readline().strip("\n")
            if len(lang_var) > 0 :
                env["LANG"] = lang_var.replace("LANG=","")

            pid = Popen('nanny-desktop-blocker', env=env).pid
        else:
            pid = Popen('nanny-desktop-blocker', env=env).pid
        
        pid_file = "/var/lib/nanny/desktop_blocks_pids/%s.%s" % (user_id, os.path.basename(session_name))
        fd = open(pid_file, "w")
        fd.write(str(pid))
        fd.close()

        pid, ret = os.waitpid(pid, 0)
        
        if os.path.exists(pid_file) :
            os.unlink(pid_file)

        return session_name, user_id, ret
开发者ID:hychen,项目名称:gnome-nanny,代码行数:31,代码来源:LinuxSessionCKFiltering.py

示例11: import_key

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import replace [as 别名]
def import_key(tempdir,kfile):
    "Imports a key to the keyring in tempdir and returns the keyid"
    import re
    out = Popen([GPG,'--homedir',tempdir,'--import',kfile],stderr=PIPE).communicate()[1].decode('utf-8')
    m = re.search("gpg: key ([0-9A-F]+).*imported",out.replace("\n"," "))
    if m:
        return m.group(1)
    raise RuntimeError("No PGP key imported")
开发者ID:usnistgov,项目名称:dane_tester,代码行数:10,代码来源:openpgpkey.py

示例12: get_service_status

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import replace [as 别名]
def get_service_status(servicename):
    try:
        service_data = Popen(["service", servicename, "status"], stdout=PIPE)
        service_data = check_output(["grep", "Active"],
                                    stdin=service_data.stdout).decode("utf-8")
        service_data = service_data.replace("\n", '')
    except CalledProcessError:
        service_data = 'Service not found'
    return service_data
开发者ID:jorgii,项目名称:lebaguette,代码行数:11,代码来源:views.py

示例13: check_source_md5

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import replace [as 别名]
    def check_source_md5(self, filename):
        if self.is_installed:
            sourcedir= Popen(["rpm", "-E", '%_sourcedir' ], stdout=subprocess.PIPE).stdout.read()[:-1]
            # replace %{name} by the specname
            package_name = Popen(["rpm", "-qp", self.filename, '--qf', '%{name}' ], stdout=subprocess.PIPE).stdout.read()
            sourcedir = sourcedir.replace("%{name}", package_name)
            sourcedir = sourcedir.replace("%name", package_name)

            src_files = glob.glob( sourcedir + '/*')
            # src_files = glob.glob(os.path.expanduser('~/rpmbuild/SOURCES/*'))
            if src_files:
                for name in src_files:
                    if filename and os.path.basename(filename) != os.path.basename(name):
                        continue
                    self.log.debug("Checking md5 for %s" % name)
                    sum,file = self._md5sum(name)
                    return sum
            else:
                print('no sources found in install SRPM')
                return "ERROR"
        else:
            print "SRPM is not installed"
            return "ERROR"
开发者ID:verdurin,项目名称:FedoraReview,代码行数:25,代码来源:__init__.py

示例14: check_exec

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import replace [as 别名]
def check_exec(executable):
    """
        Check if the executable exist
        :rtype : path
        :param executable:
        :return:
    """
    output, error = Popen(['which', executable],
                          stdout=PIPE, stderr=PIPE).communicate()
    if error:
        logging.info('%s Not found' % executable)
        return ""
    logging.info('Path to %s : %s' % (executable, output.replace("\n", "")))
    return output
开发者ID:jmpoux,项目名称:downloadboob,代码行数:16,代码来源:downloadboob_tools_generic.py

示例15: __init__

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import replace [as 别名]
 def __init__(self,dist):
     #file = open('/proc/cpuinfo').readlines()
     try:
         if dist == 'Mac OSX':
             cpu = Popen(['sysctl', '-n','machdep.cpu.brand_string'], stdout=PIPE).communicate()[0].decode('Utf-8').split('\n')[0]
             c = cpu.replace('(R)','').replace('(TM)','').replace('CPU','').split()
             cpuinfo = ' '.join(c)
         elif dist == 'FreeBSD':
             file = Popen(['sysctl', '-n','hw'], stdout=PIPE).communicate()[0].decode('Utf-8').split('\n')
             cpuinfo = re.sub('  +', ' ', file[1].replace('model name\t: ', '').rstrip('\n'))
         else:
             file = Popen(['grep', '-i', 'model name\t: ', '/proc/cpuinfo'], stdout=PIPE).communicate()[0].decode('Utf-8').split('\n')
             cpuinfo = re.sub('  +', ' ', file[0].replace('model name\t: ', ''))
     except:
         cpuinfo = 'unknown'
     self.key = 'CPU'
     self.value = cpuinfo
开发者ID:fatman2021,项目名称:pyarchey,代码行数:19,代码来源:pyarchey.py


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