簡體   English   中英

在 Windows 中捕獲 subprocess.run() 的 output

[英]Capturing output of subprocess.run() in Windows

在 Windows 和 Python3 下,我將一些使用 os.system() 的舊代碼轉換為使用os.system() subprocess.run() ,但在將 output 捕獲到 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

output 中的所有 '\t'(我想是制表符)和 '\n'(換行符)是怎么回事?

如何將結果中的字符串 '\t' 和 '\n' 轉換為實際的制表符和換行符以進行打印?

我有這樣的例子,但使用 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM