1、只有返回值,没有标准输入、输出
>>> os.system("dir")
0
2、有标准输出,但是没有返回值
默认只有标准输出,如果想输出标准错误,可以使用2>&1重定向,如果只想输出错误,而不想要标准输出,可以使用1>nul 2>&1
>>> os.popen("dir").readlines()
[' 驱动器 C 中的卷没有标签。\n', ' 卷的序列号是 F8FA-6A69\n', '\n', ' C:\\Python32 的目录\n', '\n', '2011-08-31 12:12 <DIR> .\n', '2011-08-31 12:12 <DIR> ..\n', '2011-08-31 12:12 <DIR> DLLs\n', '2011-08-31 12:12 <DIR> Doc\n', '2011-08-31 12:12 <DIR> include\n', '2011-08-31 12:11 <DIR> Lib\n', '2011-08-31 12:12 <DIR> libs\n', '2011-07-10 22:08 32,826 LICENSE.txt\n', '2011-07-10 19:34 245,116 NEWS.txt\n', '2011-07-10 21:51 26,624 python.exe\n', '2011-07-10 21:51 27,136 pythonw.exe\n', '2011-07-10 19:34 6,788 README.txt\n', '2011-08-31 12:12 <DIR> tcl\n', '2011-08-31 12:11 <DIR> Tools\n', '2011-07-10 21:51 49,664 w9xpopen.exe\n', ' 6 个文件 388,154 字节\n', ' 9 个目录 27,286,179,840 可用字节\n']
>>> os.popen("cd kkk 2>&1").readlines()
['系统找不到指定的路径。\n']
>>> os.popen("cd kkk").readlines()
[]
3、有标准输出+标准错误及返回值
subprocess
碰到一个问题,总是返回二进制字符串,不知道大家有没有好的解决办法。
已解决:具体步骤如下
import os
import sys
import subprocess
class pyexcutecmd:
def __init__(self):
self.command_str = ""
def exec_cmd(self):
try:
self.p = subprocess.Popen(self.command_str, shell=True, stderr = subprocess.PIPE, stdout = subprocess.PIPE)
(self.out, self.err) = self.p.communicate()
if sys.platform.find("win") > -1:
self.out = str(self.out,'gb2312')
self.err = str(self.err,'gb2312')
else:
self.out = str(self.out,'utf-8')
self.err = str(self.err,'utf-8')
#raise OSError('span','ok')
except (OSError, ValueError) as e:
print(self.command_str + " makes a error:",e)
return(False)
else:
return(True)
def get_returncode(self):
return(self.p.wait())
def get_stdout_all(self):
return(self.out)
def get_stderr(self):
return(self.err)
def get_stdout_lines(self):
lines = self.out.split(os.linesep)
return_lines = []
for line in lines:
if line.strip() == "":
pass
else:
return_lines.append(line)
return(return_lines)
以上为整个执行windows命令的类。