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


Python Popen.decode方法代码示例

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


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

示例1: sys_info

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import decode [as 别名]
def sys_info(request):
    template = u'''
    <h1>Revision</h1>
    %(svn_version)s
    <h1>settings path</h1>
    <pre>%(settingspath)s</pre>
    <h1>Site.objects.get_current()</h1>
    <table>
       <tr><th>id</th><td>%(site.pk)s</td></tr>
       <tr><th>domain</th><td>%(site.domain)s</td></tr>
       <tr><th>name</th><td>%(site.name)s</td></tr>
    </table>
    <h1>svn info</h1>
    <pre>%(svninfo)s</pre>
    <h1>sys.path</h1>
    <pre>%(syspath)s</pre>
    '''
    import sys
    import settings
    from django.contrib.sites.models import Site
    from subprocess import Popen, PIPE
    svn_version, svn_version_err = Popen(['svnversion', settings.PROJECT_PATH], stdout=PIPE).communicate()
    svn_version = svn_version.decode('utf-8') if svn_version else u''
    svn_version_err = svn_version_err.decode('utf-8') if svn_version_err else u''
    site = Site.objects.get_current()
    svnout, svnerr = Popen(['svn', 'info','--non-interactive','--username=anonymous','[email protected]','-r', 'HEAD', settings.PROJECT_PATH], stdout=PIPE).communicate()
    svnout = svnout.decode('utf-8') if svnout else u''
    svnerr = svnerr.decode('utf-8') if svnerr else u''
    return HttpResponse(template % {'site.pk':site.pk,
                                    'site.domain':site.domain,
                                    'site.name':site.name,
                                    'svn_version': svn_version + svn_version_err,
                                    'settingspath': settings.PROJECT_PATH,
                                    'syspath':'\n'.join(sys.path),
                                    'svninfo':svnout + svnerr})
开发者ID:frac,项目名称:opentrials,代码行数:37,代码来源:views.py

示例2: main

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import decode [as 别名]
def main():
    """Print virtualenv and python version."""
    workon_home = os.environ.get('WORKON_HOME')
    workon_home = Path(workon_home)

    for virtualenv in workon_home.iterdir():
        if virtualenv.is_dir():
            for python_bin in Path(f'{virtualenv}/bin/').iterdir():
                if python_bin.name == 'python':
                    virtual_environment = str(virtualenv).rpartition('/')[-1]
                    command = [f'{python_bin}',
                               '-c',
                               "import sys;print(sys.version.split()[0]);"
                               ]
                    stdout, _ = Popen(command, stdout=PIPE).communicate()
                    stdout = stdout.decode('utf-8')
                    python_version = stdout.strip()
                if python_bin.name == 'pip':
                    command = [f'{python_bin}',
                               'freeze'
                               ]
                    stdout, _ = Popen(command, stdout=PIPE).communicate()
                    stdout = stdout.decode('utf-8')
                    packages = [p.strip() for p in stdout.split()]
            with open(f'virtualenvs-{os.uname()[1].split(".")[0]}.md', 'a') as f:
                f.write(template.render(virtualenv=virtual_environment,
                                        version=python_version,
                                        packages=packages))
开发者ID:christopher-burke,项目名称:python-scripts,代码行数:30,代码来源:virtualenv_env_requirements.py

示例3: createoconv

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import decode [as 别名]
def createoconv(scene, frame, sim_op, simnode, **kwargs):
    fbase = "{0}-{1}".format(scene['viparams']['filebase'], frame)

    with open("{}.oct".format(fbase), "wb") as octfile:
        err =  Popen("oconv -w -".split(), stdin = PIPE, stderr = PIPE, stdout = octfile).communicate(input = simnode['radfiles'][str(frame)].encode(sys.getfilesystemencoding()))[1]
        if err and 'fatal -' in err.decode():
            sim_op.report({'ERROR'}, 'Oconv conversion failure: {}'.format(err.decode()))
            return 'CANCELLED'
开发者ID:rgsouthall,项目名称:vi-suite04,代码行数:10,代码来源:livi_export.py

示例4: test_rosnode

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import decode [as 别名]
    def test_rosnode(self):
        topics = ['/chatter', '/foo/chatter', '/bar/chatter']
        
        # wait for network to initialize
        rospy.init_node('test')
        nodes = ['/talker', '/foo/talker', '/bar/talker', rospy.get_caller_id()]
        
        for i, t in enumerate(topics):
            rospy.Subscriber(t, std_msgs.msg.String, self.callback, i)
        all = set(range(0, len(topics)))

        timeout_t = time.time() + 10.
        while time.time() < timeout_t and self.vals != all:
            time.sleep(0.1)
        self.assertEquals(self.vals, all, "failed to initialize graph correctly")
            

        # network is initialized
        cmd = 'rosnode'

        # list
        # - we aren't matching against the core services as those can make the test suites brittle
        output = Popen([cmd, 'list'], stdout=PIPE).communicate()[0]
        output = output.decode()
        l = set(output.split())
        for t in nodes:
            self.assert_(t in l, "%s not in %s"%(t, l))

        output = Popen([cmd, 'list', '-a'], stdout=PIPE).communicate()[0]
        output = output.decode()
        l = set(output.split())
        for t in nodes:
            for e in l:
                if t in e:
                    break
            else:
                self.fail("did not find [%s] in list [%s]"%(t, l))

        output = Popen([cmd, 'list', '-u'], stdout=PIPE).communicate()[0]
        output = output.decode() 
        l = set(output.split())
        self.assert_(len(l), "list -u is empty")
        for e in l:
            self.assert_(e.startswith('http://'))

        for name in nodes:
            # type
            output = Popen([cmd, 'info', name], stdout=PIPE).communicate()[0]
            output = output.decode()
            # not really validating output as much as making sure it's not broken
            self.assert_(name in output)
            self.assert_('chatter' in output)
            self.assert_('Publications' in output)
            self.assert_('Subscriptions' in output)                        

            if 0:
                #ping
                stdout, stderr = run_for([cmd, 'ping', name], 3.)
开发者ID:Aand1,项目名称:ROSCH,代码行数:60,代码来源:test_rosnode_command_online.py

示例5: tracked_files

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import decode [as 别名]
def tracked_files():
    git_cmd = git_ls_tree()
    files = Popen(git_cmd,
                  shell=True,
                  stdout=PIPE).stdout.read()
    files = files.decode().split('\n')
    return files
开发者ID:christopher-burke,项目名称:python-scripts,代码行数:9,代码来源:readme.py

示例6: lookfor

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import decode [as 别名]
def lookfor(file, pattern, timepattern, timezone, interval):
    """
    Look for a pattern in given files within interval
    """
    message = ''
    timestamps = within(timezone, timepattern, interval)
    since = localtime(timezone).strftime("%H:%M")
    abspath = os.path.abspath(file)
    heading = ("### Looking for %s log in %s "
               "the last %d minutes since %s %s ###\n" %
               (pattern, abspath, interval, since, timezone))
    message = message + heading

    for timestamp in timestamps:
        # add `:` so it will match `HH:MM:`
        # not `HH:MM` which can be mislead to `MM:SS`
        patterns = timestamp + ':' + '.*' + pattern
        stdout, stderr = Popen(['grep', patterns, file],
                               stdout=PIPE).communicate()
        gotcha = stdout.decode("utf-8")

        if gotcha == '':
            print("### Can't find any %s log at %s %s in %s ###" %
                  (pattern, timestamp, timezone, file))
        else:
            print("##### Found matching %s log at %s %s in %s #####" %
                  (pattern, timestamp, timezone, file))
            message = message + gotcha + "\n"

    return message
开发者ID:xoxzo,项目名称:xoxzo.logwatch,代码行数:32,代码来源:main.py

示例7: encrypt

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import decode [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

示例8: extract_corpus

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import decode [as 别名]
def extract_corpus(docs=DOCS, corpus=CORPUS):
    """
    Extracts a text corpus from the PDF documents and writes them to disk.
    """
    # Create corpus directory if it doesn't exist.
    if not os.path.exists(corpus):
        os.mkdir(corpus)

    # For each PDF path, use pdf2txt to extract the text file.
    for path in get_documents(docs):
        # print 'Path: ', path

        # Call the subprocess command (must be on your path)
        # document = subprocess.check_output(
        #     ['pdftotxt', path, '-']
        # )
        document = Popen(['pdftotext', path, '-'], stdout=PIPE).communicate()[0]
        # print document
    
        # Encode UTF-u and remove non-printable characters
        document = filter(
            lambda char: char in string.printable,
            unicodedata.normalize('NFKD', document.decode('utf-8'))
        )

        # Write the document out to the corpus directory
        fname = os.path.splitext(os.path.basename(path))[0] + ".txt"
        outpath = os.path.join(corpus, fname)

        with codecs.open(outpath, 'w') as f:
            f.write(document)
开发者ID:goldin2008,项目名称:Research_in_NLP,代码行数:33,代码来源:extract_NER.py

示例9: test_contact

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import decode [as 别名]
 def test_contact(self):
     """ Make sure optional contact details can be set """
     # add a logging handler that captures the info log output
     log_output = StringIO()
     debug_handler = logging.StreamHandler(log_output)
     acme_tiny.LOGGER.addHandler(debug_handler)
     # call acme_tiny with new contact details
     old_stdout = sys.stdout
     sys.stdout = StringIO()
     result = acme_tiny.main([
         "--account-key", KEYS['account_key'].name,
         "--csr", KEYS['domain_csr'].name,
         "--acme-dir", self.tempdir,
         "--directory-url", self.DIR_URL,
         "--contact", "mailto:[email protected]", "mailto:[email protected]",
     ])
     sys.stdout.seek(0)
     crt = sys.stdout.read().encode("utf8")
     sys.stdout = old_stdout
     log_output.seek(0)
     log_string = log_output.read().encode("utf8")
     # make sure the certificate was issued and the contact details were updated
     out, err = Popen(["openssl", "x509", "-text", "-noout"], stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate(crt)
     self.assertIn("Issuer: CN=Fake LE Intermediate", out.decode("utf8"))
     self.assertIn("Updated contact details:\nmailto:[email protected]\nmailto:[email protected]", log_string.decode("utf8"))
     # remove logging capture
     acme_tiny.LOGGER.removeHandler(debug_handler)
开发者ID:DinosaurDad,项目名称:acme-tiny,代码行数:29,代码来源:test_module.py

示例10: lookfor

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import decode [as 别名]
def lookfor(files, pattern, interval):
    """
    Look for a pattern in given files within interval
    """
    message = ''
    timestamps = within(interval)

    for f in files.strip().split(","):
        abspath = os.path.abspath(f)
        heading = ("### Looking for %s log in %s within "
                   "the last %d minutes ###\n" %
                   (pattern, abspath, interval))
        message = message + heading

        for timestamp in timestamps:
            patterns = timestamp + '.*' + pattern
            stdout, stderr = Popen(['grep', patterns, f],
                                   stdout=PIPE).communicate()
            gotcha = stdout.decode("utf-8")

            if gotcha == '':
                print("### Can't find any %s log at %s in %s ###" %
                      (pattern, timestamp, f))
            else:
                print("##### Found matching %s log at %s in %s #####" %
                      (pattern, timestamp, f))
                message = message + gotcha + "\n"

    return message
开发者ID:za,项目名称:xoxzo.logwatch,代码行数:31,代码来源:main.py

示例11: list_outdated_packages

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import decode [as 别名]
def list_outdated_packages(python):
    """
    Get a list of outdated packages
    :param str python: Path to the python executable
    :return list: Outdated Python packages if any exist; empty list otherwise
    """
    # Run the command and put output in tmp_packs
    logging.debug("[{0}] Running {0} -m pip list -o".format(python))
    try:
        outdated_packages = Popen([python, "-m", "pip", "list", "-o"], stdout=PIPE, stderr=PIPE).communicate()[0]
    except KeyboardInterrupt:
        logging.warning("[{}] Keyboard interrupt detected; Skipping this version...".format(python))
        return []
    except Exception as exp:
        logging.error("[{}] Exception encountered while listing outdated packages. {}".format(python, exp))
        return []

    # Outdated packages come in the form of <package_name> <version>\n
    # So it is first split by newlines and then only the package name is used
    packs = []
    if outdated_packages:
        # noinspection PyTypeChecker
        packs = [pkg.split()[0].lower() for pkg in outdated_packages.decode('utf-8').split('\n')[2:]
                 if pkg.split() and pkg.split()[0]]

    return packs
开发者ID:just-another-user,项目名称:sys-tools,代码行数:28,代码来源:pipdate.py

示例12: create_history_frequencies

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import decode [as 别名]
def create_history_frequencies():
	home       = path.expanduser('~')
	logger.debug("user home path  = '%s'" % home)
	shell_byte = Popen("echo $SHELL", shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT).communicate()[0]
	shell_path = shell_byte.decode("utf-8").strip()
	shell_name = shell_path.rsplit("/", 1)[-1]
	logger.debug("shell path = '%s'" % shell_path)
	logger.debug("shell name = '%s'" % shell_name)

	words = {}

	if shell_name in ["bash", "sh", "ksh"]:
		if   shell_name in ["ksh"]:        filepath = home + "/.sh_history"
		elif shell_name in ["bash", "sh"]: filepath = home + "/.bash_history"
		else: raise Exception()
		with codecs.open(filepath, "r", encoding='utf-8', errors='ignore') as f:
			for line in f:
				word = command_pattern.sub("", line).strip()
				words[word] = words.get(word, 0) + 1

	elif shell_name in ["zsh"]:
		with codecs.open(home + "/.zsh_history", "r", encoding='utf-8', errors='ignore') as f:
			for line in f:
				parts = line.split(";", 1)
				if len(parts) < 2: continue
				word = command_pattern.sub("", parts[1]).strip()
				words[word] = words.get(word, 0) + 1

	elif shell_name in ["csh"]:
		logger.warning("Not implemented!") # TODO:

	else:
		raise Exception("Unknown shell : '%1'" % shell)

	return tuple(words.items())
开发者ID:hatappo,项目名称:command_history_wordcloud,代码行数:37,代码来源:command_history_wordcloud.py

示例13: hg_branch_iter_local

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import decode [as 别名]
def hg_branch_iter_local(repo):
    cmd = ('hg', '-y', 'branches', '-c', '-R', repo)
    out = Popen(cmd, stdout=PIPE).communicate()[0]
    out = out.decode('utf8').split(linesep)

    out = (re.split('\s+', i, 1) for i in out if i)
    return (name for name, rev in out)
开发者ID:piotrsynowiec,项目名称:jenkins-autojobs,代码行数:9,代码来源:hg.py

示例14: run

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import decode [as 别名]
def run(cmd,fail=Host+":"+PathShort+" \$ "):
	res, err = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()
	err_string = err.decode('utf-8')
	if 'fatal' in err_string:
		print fail
		sys.exit(0)
	return res.decode('utf-8')
开发者ID:parrt,项目名称:bash-git-prompt,代码行数:9,代码来源:parrt-prompt.py

示例15: test_dump

# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import decode [as 别名]
    def test_dump(self):
        '''test_add_delete will test the add and delete functions
        '''
        print('Testing json DUMP')
        from sutils import write_json, read_json

        print('Case 1: Dumping file.')

        jsondump = {'HELLO':'KITTY',
                    'BATZ':'MARU',
                    'MY':'MELODY' }
        write_json(jsondump,self.file)
        self.assertTrue(os.path.exists(self.file))
        
        script_path = "%s/helpers/json/dump.py" %(self.here)
        if VERSION == 2:
            testing_command = ["python2",script_path,'--file',self.file]
        else:
            testing_command = ["python3",script_path,'--file',self.file]

        output = Popen(testing_command,stderr=PIPE,stdout=PIPE)
        t = output.communicate()[0],output.returncode
        result = {'message':t[0],
                  'return_code':t[1]}
        self.assertEqual(result['return_code'],0)

        output = result['message']
        if isinstance(output,bytes):
            output = output.decode(encoding='UTF-8')

        dump = ['HELLO:"KITTY"', 'BATZ:"MARU"', 'MY:"MELODY"']
        result = output.strip('\n').split('\n')[-3:]
        for res in result:
            self.assertTrue(res in dump)
开发者ID:aculich,项目名称:singularity,代码行数:36,代码来源:test_json.py


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