zoukankan      html  css  js  c++  java
  • subprocess 模块 与终端相互交互

    import  subprocess 
    '''
    sh-3.2# ls /Users/egon/Desktop |grep txt$
    mysql.txt
    tt.txt
    事物.txt
    '''
    #1 Linux下,通过python运行终端代码:
    res1=subprocess.Popen('ls /Users/jieli/Desktop',
                          shell=True,
                          stdout=subprocess.PIPE)
    res=subprocess.Popen('grep txt$',
                          shell=True,
                          stdin=res1.stdout,  # res1.stdout是res.stdin
                          stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE)  
    print(res.stdout.read().decode('utf-8'))
    print(res.stderr.read().decode('utf-8'))
    #等同于上面,但是上面的优势在于,一个数据流可以和另外一个数据流交互,可以通过爬虫得到结果然后交给grep
    res1=subprocess.Popen('ls /Users/jieli/Desktop |grep txt$',
                          shell=True,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE)
    print(res1.stdout.read().decode('utf-8'))
    print(res.stderr.read().decode('utf-8'))
    
    #2 windows下,通过python运行终端代码:
    # dir | findstr 'test*'
    # dir | findstr 'txt$'
    import subprocess
    res1=subprocess.Popen(r'dir C:UsersAdministratorPycharmProjects	est函数备课',shell=True,stdout=subprocess.PIPE)
    res=subprocess.Popen('findstr test*',shell=True,stdin=res1.stdout,
                     stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    
    print(res.stdout.read().decode('gbk')) 
    print(res.stderr.read().decode('gbk')) #subprocess使用当前系统默认编码,得到结果为bytes类型,在windows下需要用gbk解码
  • 相关阅读:
    如何判断两个数组是否相等?
    正则表达式
    开发板 Linux驱动视频 驱动是什么
    关于模型的评估
    Python画图参数设置
    Python图片的横坐标汉字
    矩阵的点成和叉乘
    svd 奇异值分解
    Python的主成分分析PCA算法
    论文参考文献格式
  • 原文地址:https://www.cnblogs.com/snailgirl/p/9417367.html
Copyright © 2011-2022 走看看