python将stderr重定向到文件不起作用

时间:2018-02-11 00:52:43

标签: python subprocess os.system

我有一个运行带有不同输入的程序的python脚本。我想将stderr输出重定向到文件并构建一个html文件。

我的问题是,我的脚本运行,但是stderr没有写入文件,就像它在某处消失了。我尝试过使用subprocess.call#!/usr/bin/python import os import subprocess indir = 'good' name = 'good' count = 0 badcount = 0 file_num = 0 with open('output.html', 'w') as ofh: test = open('output.html') ofh.write("""<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> </head> <body>\n""") for i in range(0, 2): for root, dirs, filenames in os.walk(indir): for f in filenames: if f.endswith('.tig'): prog = './../src/tc ' + indir + '/' + f prog1 = './../src/tc' prog2 = indir + '/' + f ofh.write('%s <br>\n' % (f)) x = os.system('%s &>output.html' % (prog)) x = subprocess.call([prog1, prog2], stderr=test) if x == 0: count += 1 else: ofh.write("<br>\n") badcount += 1 file_num += 1 ofh.write("<br>\n") ofh.write('%s /%s good tests found in %s folder<br>\n' % (count, file_num, name)) ofh.write('%s /%s bad tests found in %s folder<br>\n' % (badcount, file_num, name)) count = 0 badcount = 0 file_num = 0 if i == 0: indir = 'syntax' name = 'syntax' elif i == 1: indir = 'bind' name = 'bind' elif i == 2: indir = 'type' name = 'type' ofh.write(""" </body> </html>""")

# import libraries
import csv
import urllib2
from bs4 import BeautifulSoup

# specify the url
quote_page = 'http://www.bkfrem.dk/default.asp?id=19'

# query the website and return the html to the variable ‘page’
page = urllib2.urlopen(quote_page)

# parse the html using beautiful soup and store in variable soup
soup = BeautifulSoup(page, 'html.parser')

# create CSV file
csvfile = csv.writer(open('firsteam.csv', 'w'))
csvfile.writerow(["Name", "Position"])

# take out the <div> of name and get its value
items = soup.find_all('div', attrs={'class': 'visTruppenContainer'})

for i in range(len(items)):

    playerInfo = items[i].getText(separator=u' ')
    imageURL = items[1].find('img')['src']
    csvfile.writerow([playerInfo, imageURL])
    print (playerInfo)
    print (imageURL)

这里我用os.system和subprocess.call进行了2次尝试,有谁知道会发生什么?或者我做错了什么?

1 个答案:

答案 0 :(得分:0)

您可能希望使用Popen中的subprocess并将stdout和stderr重定向到PIPE

p = Popen(cmd, stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate()

这是一个模拟代码,我运行的命令会产生捕获到html文件中的错误。

from subprocess import Popen, PIPE

with open('output.html', 'w') as ofh:
    ofh.write("""<body>\n""")

    cmd = 'python file.png' #this will produce error
    p = Popen(cmd, stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate()

    ofh.write("""{}""".format(stderr))
    ofh.write("""</body>""")

哪会导致以下错误:

C:\python file.png
  File "file.png", line 1
SyntaxError: Non-ASCII character '\x89' in file file.png on line 1, but no encod
ing declared; see http://python.org/dev/peps/pep-0263/ for details

在html文件中捕获的内容

enter image description here