Python正课62 —— subprocess模块

本文内容皆为作者原创,如需转载,请注明出处:https://www.cnblogs.com/xuexianqi/p/12604353.html

一:subprocess

在Windows平台和Linux平台不同

Windows平台

import subprocess

obj = subprocess.Popen(r'E:\Python学习相关\我的博客文件\Python正课内容',
                       shell=True,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE,
                       )
print(obj)  # <subprocess.Popen object at 0x02FB2FE8>
res = obj.stdout.read()
print(res)  # b''

err_res = obj.stderr.read() #'E:\Python学习相关\我的博客文件\Python正课内容' 不是内部或外部命令,也不是可运行的程序或批处理文件。
print(err_res.decode('gbk'))  # b"'E:\\Python\xd1\xa7\xcf\xb0\xcf\xe0\xb9\xd8\\\xce\xd2\xb5\xc4\xb2\xa9\xbf\xcd\xce\xc4\xbc\xfe\\Python\xd5\xfd\xbf\xce\xc4\xda\xc8\xdd' \xb2\xbb\xca\xc7\xc4\xda\xb2\xbf\xbb\xf2\xcd\xe2\xb2\xbf\xc3\xfc\xc1\xee\xa3\xac\xd2\xb2\xb2\xbb\xca\xc7\xbf\xc9\xd4\xcb\xd0\xd0\xb5\xc4\xb3\xcc\xd0\xf2\r\n\xbb\xf2\xc5\xfa\xb4\xa6\xc0\xed\xce\xc4\xbc\xfe\xa1\xa3\r\n"
print(err_res)  # b"'E:\\Python\xd1\xa7\xcf\xb0\xcf\xe0\xb9\xd8\\\xce\xd2\xb5\xc4\xb2\xa9\xbf\xcd\xce\xc4\xbc\xfe\\Python\xd5\xfd\xbf\xce\xc4\xda\xc8\xdd' \xb2\xbb\xca\xc7\xc4\xda\xb2\xbf\xbb\xf2\xcd\xe2\xb2\xbf\xc3\xfc\xc1\xee\xa3\xac\xd2\xb2\xb2\xbb\xca\xc7\xbf\xc9\xd4\xcb\xd0\xd0\xb5\xc4\xb3\xcc\xd0\xf2\r\n\xbb\xf2\xc5\xfa\xb4\xa6\xc0\xed\xce\xc4\xbc\xfe\xa1\xa3\r\n"

Linux平台

import  subprocess

'''
sh-3.2# ls /Users/egon/Desktop |grep txt$
mysql.txt
tt.txt
事物.txt
'''

res1=subprocess.Popen('ls /Users/jieli/Desktop',shell=True,stdout=subprocess.PIPE)
res=subprocess.Popen('grep txt$',shell=True,stdin=res1.stdout,
                 stdout=subprocess.PIPE)

print(res.stdout.read().decode('utf-8'))

#等同于上面,但是上面的优势在于,一个数据流可以和另外一个数据流交互,可以通过爬虫得到结果然后交给grep
res1=subprocess.Popen('ls /Users/jieli/Desktop |grep txt$',shell=True,stdout=subprocess.PIPE)
print(res1.stdout.read().decode('utf-8'))
posted @ 2020-03-31 12:31  轻描丨淡写  阅读(364)  评论(0编辑  收藏  举报