subprocess
在Windows平台和Linux平台不同
Windows平台
import subprocess
obj = subprocess.Popen(r'E: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学习相关我的博客文件' 不是内部或外部命令,也不是可运行的程序或批处理文件。
print(err_res.decode('gbk')) # b"'E:\Pythonxd1xa7xcfxb0xcfxe0xb9xd8\xcexd2xb5xc4xb2xa9xbfxcdxcexc4xbcxfe\Pythonxd5xfdxbfxcexc4xdaxc8xdd' xb2xbbxcaxc7xc4xdaxb2xbfxbbxf2xcdxe2xb2xbfxc3xfcxc1xeexa3xacxd2xb2xb2xbbxcaxc7xbfxc9xd4xcbxd0xd0xb5xc4xb3xccxd0xf2
xbbxf2xc5xfaxb4xa6xc0xedxcexc4xbcxfexa1xa3
"
print(err_res) # b"'E:\Pythonxd1xa7xcfxb0xcfxe0xb9xd8\xcexd2xb5xc4xb2xa9xbfxcdxcexc4xbcxfe\Pythonxd5xfdxbfxcexc4xdaxc8xdd' xb2xbbxcaxc7xc4xdaxb2xbfxbbxf2xcdxe2xb2xbfxc3xfcxc1xeexa3xacxd2xb2xb2xbbxcaxc7xbfxc9xd4xcbxd0xd0xb5xc4xb3xccxd0xf2
xbbxf2xc5xfaxb4xa6xc0xedxcexc4xbcxfexa1xa3
"
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'))