我的Python自学之路测试员的那点事

python 执行外部命令的几种方式

2020-08-21  本文已影响0人  望月成三人

os.system

t2 = os.system("1adb devices")
t3 = os.system("adb devices")
print(t2)  # 打印为1
print(t3) # 打印为0

subprocess.call

import subprocess
t = subprocess.call('adb devices')
print(t) # 打印为0

os.popen

output = os.popen('adb devices')
print(output.read()) # 得到List of devices attached

subprocess.Popen

shell参数

subprocess.Popen("cat test.txt", shell=True)
这是因为它相当于
subprocess.Popen(["/bin/sh", "-c", "cat test.txt"])

stdin stdout stderr 参数

pipe=subprocess.Popen("adb devices",shell=True,stdout=subprocess.PIPE).stdout
print(pipe.read()) # 得到值b'List of devices attached\r\n\r\n'
cmd = "adb shell ls /sdcard/ | findstr aa.png"  
fhandle = open(r"e:\aa.txt", "w")  
pipe = subprocess.Popen(cmd, shell=True, stdout=fhandle).stdout  
fhandle.close()
#!/usr/bin/env python

import subprocess

child1 = subprocess.Popen(["ls","-l"], stdout=subprocess.PIPE)
child2 = subprocess.Popen(["wc"], stdin=child1.stdout,stdout=subprocess.PIPE)
out = child2.communicate()
print out
import subprocess
child = subprocess.Popen(["cat"], stdin=subprocess.PIPE)
child.communicate("vamei") //()不为空,则写入subprocess.PIPE,为空,则从subprocess.PIPE读取
import subprocess


# print ’popen3:’

def external_cmd(cmd, msg_in=''):
    try:
        proc = subprocess.Popen(cmd,
                                shell=True,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                )
        stdout_value, stderr_value = proc.communicate(msg_in)
        return stdout_value, stderr_value
    except ValueError as err:
        # log("ValueError: %s" % err)
        return None, None
    except IOError as err:
        # log("IOError: %s" % err)
        return None, None


if __name__ == '__main__':
    stdout_val, stderr_val = external_cmd('dir')
    print ('Standard Output: %s' % stdout_val)
    print ('Standard Error: %s' % stderr_val)
p=subprocess.Popen("dir", shell=True)  
p.wait()

commands.getstatusoutput

上一篇下一篇

猜你喜欢

热点阅读