subprocess使用方法

代码示例:

#!/usr/bin/env python

import subprocess
import sys

def print_file_type(file_name):
    cmd = ['file ' + file_name]
    p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    stdout, stderr = p.communicate()
    print 'stdout:', stdout
    print 'stderr:', stderr
    print 'return code:', p.returncode

def usage():    
    print sys.argv[0], "file_name"
  
if __name__=="__main__":    
    argc = len(sys.argv)    
    if argc != 2:    
        usage()    
        sys.exit(-1)    
    
    file_name = sys.argv[1]  
    print_file_type(file_name)

运行示例:

flying-bird@flyingbird:~/examples/python/print_file_type$ ./print_file_type.py ./print_file_type.py
stdout: ./print_file_type.py: Python script, ASCII text executable

stderr: None
return code: 0
flying-bird@flyingbird:~/examples/python/print_file_type$ ./print_file_type.py ../../cpp/read_write_read/a.out 
stdout: ../../cpp/read_write_read/a.out: ELF 32-bit LSB  executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=5520f400b4561a89d9d2b712a8b288ef72411a49, not stripped

stderr: None
return code: 0
flying-bird@flyingbird:~/examples/python/print_file_type$ file ./print_file_type.py
./print_file_type.py: Python script, ASCII text executable
flying-bird@flyingbird:~/examples/python/print_file_type$ file ../../cpp/read_write_read/a.out 
../../cpp/read_write_read/a.out: ELF 32-bit LSB  executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=5520f400b4561a89d9d2b712a8b288ef72411a49, not stripped
flying-bird@flyingbird:~/examples/python/print_file_type$ 

参考资料:

Android源码的build/tools/releasetools/common.py的如下部分:

def Run(args, **kwargs):
  """Create and return a subprocess.Popen object, printing the command
  line on the terminal if -v was specified."""
  if OPTIONS.verbose:
    print "  running: ", " ".join(args)
  return subprocess.Popen(args, **kwargs)


def GetKeyPasswords(keylist):
  """Given a list of keys, prompt the user to enter passwords for
  those which require them.  Return a {key: password} dict.  password
  will be None if the key has no password."""

  no_passwords = []
  need_passwords = []
  key_passwords = {}
  devnull = open("/dev/null", "w+b")
  for k in sorted(keylist):
    # We don't need a password for things that aren't really keys.
    if k in SPECIAL_CERT_STRINGS:
      no_passwords.append(k)
      continue

    p = Run(["openssl", "pkcs8", "-in", k+OPTIONS.private_key_suffix,
             "-inform", "DER", "-nocrypt"],
            stdin=devnull.fileno(),
            stdout=devnull.fileno(),
            stderr=subprocess.STDOUT)
    p.communicate()
    if p.returncode == 0:
      # Definitely an unencrypted key.
      no_passwords.append(k)
    else:
      p = Run(["openssl", "pkcs8", "-in", k+OPTIONS.private_key_suffix,
               "-inform", "DER", "-passin", "pass:"],
              stdin=devnull.fileno(),
              stdout=devnull.fileno(),
              stderr=subprocess.PIPE)
      stdout, stderr = p.communicate()
      if p.returncode == 0:
        # Encrypted key with empty string as password.
        key_passwords[k] = ''
      elif stderr.startswith('Error decrypting key'):
        # Definitely encrypted key.
        # It would have said "Error reading key" if it didn't parse correctly.
        need_passwords.append(k)
      else:
        # Potentially, a type of key that openssl doesn't understand.
        # We'll let the routines in signapk.jar handle it.
        no_passwords.append(k)
  devnull.close()

  key_passwords.update(PasswordManager().GetPasswords(need_passwords))
  key_passwords.update(dict.fromkeys(no_passwords, None))
  return key_passwords




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值