在Windows中捕获subprocess.run()的输出

时间:2019-10-24 04:11:54

标签: python windows subprocess

在Windows和Python3下,我正在将一些使用os.system()的旧代码转换为使用subprocess.run(),但是在将输出捕获到stdout和stderr时遇到了麻烦。

这就是我从简单的dir c:\中得到的结果:

r = subprocess.run(['dir', 'c:\\'], check=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

r.stdout
Out[56]: '$GetCurrent\t\t  Program\\ Files\t       Users\t   cygwin64\n$Recycle.Bin\t\t  Program\\ Files\\ (x86)        WPy64-3740  findEm\nBOOTNXT\t\t\t  ProgramData\t\t       Windows\t   microchip\nBrother\t\t\t  Program_Files\t\t       antiword    pagefile.sys\nDocuments\\ and\\ Settings  Recovery\t\t       bin\t   swapfile.sys\nPerfLogs\t\t  System\\ Volume\\ Information  bootmgr\n'

type(r.stdout)
Out[57]: str

输出中的所有'\ t'(我想是标签)和'\ n'(换行符)是什么?

如何将结果中的字符串'\ t'和'\ n'转换为实际的制表符和换行符以进行打印?

1 个答案:

答案 0 :(得分:0)

我有这样的例子,但是使用sqlcmd:

from subprocess import Popen, PIPE, STDOUT

connection_string = 'sqlcmd -S %s -U %s -P %s -d %s -i %s -r0' %(self.host,self.user,self.password,self.db,file)
session = Popen(connection_string, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = session.communicate()
#Where stderr is the error
print(stderr)
#Where is the output 
print(stdout)
相关问题