Python3:如何将输出打印到控制台和文件
所以基本上我还在学习Python编程,目前正在使用我在github上找到的一些代码 基本上,代码在执行时工作正常,它将输出打印到终端/控制台。但是,我想将输出保存到文件中,因此遵循了一些教程并成功地将输出保存到文件中,但输出没有显示在终端中 我的问题是,如何执行这个python脚本在终端上显示输出,同时将输出写入.txt文件 下面是我正在编写的python代码:Python3:如何将输出打印到控制台和文件,python,windows,file,python-3.x,terminal,Python,Windows,File,Python 3.x,Terminal,所以基本上我还在学习Python编程,目前正在使用我在github上找到的一些代码 基本上,代码在执行时工作正常,它将输出打印到终端/控制台。但是,我想将输出保存到文件中,因此遵循了一些教程并成功地将输出保存到文件中,但输出没有显示在终端中 我的问题是,如何执行这个python脚本在终端上显示输出,同时将输出写入.txt文件 下面是我正在编写的python代码: import os import warnings import argparse import sys import unicode
import os
import warnings
import argparse
import sys
import unicodedata
from PIL import Image
COLORS = [
[0, (255,255,255), '97', 'white'],
[1, (0,0,0), '30', 'black'],
[2, (0,0,127), '34', 'blue'],
[3, (0,147,0), '32', 'green'],
[4, (255,0,0), '91', 'light red'],
[5, (127,0,0), '31', 'brown'],
[6, (156,0,156), '35', 'purple'],
[7, (252,127,0), '33', 'orange'],
[8, (255,255,0), '93', 'yellow'],
[9, (0,252,0), '92', 'light green'],
[10, (0,147,147), '36', 'cyan'],
[11, (0,255,255), '96', 'light cyan'],
[12, (0,0,252), '94', 'light blue'],
[13, (255,0,255), '95', 'pink'],
[14, (127,127,127), '90', 'grey'],
[15, (210,210,210), '37', 'light grey']
]
def convert(img, doColor=True, renderIRC=True, cutoff=50, size=1.0, invert=False, alphaColor=(0,0,0)):
i = Image.open(img)
WIDTH = int(90*size)
HIGHT = int(40*size)
# Resize the image to fix bounds
s = i.size
if s[0]==0 or s[1]==0 or (float(s[0])/float(WIDTH))==0 or (float(s[1])/float(HIGHT))==0:
return []
ns = (WIDTH,int(s[1]/(float(s[0])/float(WIDTH))))
if ns[1]>HIGHT:
ns = (int(s[0]/(float(s[1])/float(HIGHT))),HIGHT)
i2 = i.resize(ns)
bimg = []
for r in range(0,i2.size[1],4):
line = u''
lastCol = -1
for c in range(0,i2.size[0],2):
val = 0
i = 0
cavg = [0,0,0]
pc = 0
for ci in range(0,4):
for ri in range(0,3 if ci<2 else 1):
# Convert back for the last two pixels
if ci>=2:
ci-=2
ri=3
# Retrieve the pixel data
if c+ci<i2.size[0] and r+ri<i2.size[1]:
p = i2.getpixel((c+ci,r+ri))
alpha = p[3] if len(p)>3 else 1
if invert and alpha>0:
p = map(lambda x: 255-x, p)
elif alpha==0:
p = alphaColor
else:
p = (0,0,0)
# Check the cutoff value and add to unicode value if it passes
luma = (0.2126*float(p[0]) + 0.7152*float(p[1]) + 0.0722*float(p[2]))
pv = sum(p[:3])
if luma > cutoff:
val+=1<<i
cavg = map(sum,zip(cavg,p))
pc+=1
i += 1
if doColor and pc>0:
# Get the average of the 8 pixels
cavg = map(lambda x:x/pc,cavg)
# Find the closest color with geometric distances
colorDist = lambda c:sum(map(lambda x:(x[0]-x[1])**2,zip(cavg,c[1])))
closest = min(COLORS, key=colorDist)
if closest[0]==1 or lastCol==closest[0]:
# Check if we need to reset the color code
if lastCol!=closest[0] and lastCol!=-1:
line+='\x03' if renderIRC else '\033[0m'
line += unichr(0x2800+val)
else:
# Add the color escape to the first character in a set of colors
if renderIRC:
line += ('\x03%u'%closest[0])+unichr(0x2800+val)
else:
line += ('\033[%sm'%closest[2])+unichr(0x2800+val)
lastCol = closest[0]
else:
# Add the offset from the base braille character
line += unichr(0x2800+val)
bimg.append(line)
return bimg
if __name__=='__main__':
ap = argparse.ArgumentParser()
ap.add_argument('file', help='The image file to render')
ap.add_argument('-c',type=int,default=100, help='The luma cutoff amount, from 0 to 255. Default 50')
ap.add_argument('-s', type=float, default=1.0, help='Size modifier. Default 1.0x')
ap.add_argument('--nocolor', action="store_true", default=False, help='Don\'t use color')
ap.add_argument('--irc', action="store_true", default=False, help='Use IRC color escapes')
ap.add_argument('--invert', action="store_true", default=False, help='Invert the image colors')
ap.add_argument('--background', default='black', help='The color to display for full alpha transparency')
ap.add_argument('-f', help="Write to text file")
args = ap.parse_args()
alphaColor = (0,0,0)
for c in COLORS:
if c[3].lower() == args.background:
alphaColor = c[1]
break
for u in convert(args.file,doColor=not args.nocolor, renderIRC=args.irc, cutoff=args.c, size=args.s, invert=args.invert, alphaColor=alphaColor):
#sys.stdout = open('I put my path here to .txt file','a')
print u.encode('utf-8')
#sys.stdout.close()
导入操作系统
进口警告
导入argparse
导入系统
导入Unicode数据
从PIL导入图像
颜色=[
[0,(255255),'97','white'],
[1,(0,0,0),'30','black'],
[2,(0,0127),“34”,“蓝色”],
[3,(0147,0),“32”,“绿色”],
[4,(255,0,0),'91','浅红色'],
[5,(127,0,0),'31','brown'],
[6,(156,0156),“35”,“紫色”],
[7,(252127,0),'33','orange'],
[8,(255255,0),'93','黄色'],
[9,(0252,0),'92','浅绿色'],
[10,(0147147),'36','青色'],
[11,(0255255),'96','浅青色'],
[12,(0,0252),'94','浅蓝色'],
[13,(255,0255),‘95’,‘粉红’],
[14,(127127),“90”,“灰色”],
[15,(210210),'37','浅灰色']
]
def转换(img,doColor=True,renderIRC=True,截止=50,大小=1.0,反转=False,alphaColor=(0,0,0)):
i=图像打开(img)
宽度=整数(90*尺寸)
高度=整数(40*尺寸)
#调整图像大小以固定边界
s=i.尺寸
如果s[0]==0或s[1]==0或(浮点(s[0])/浮点(宽度))==0或(浮点(s[1])/浮点(高))==0:
返回[]
ns=(宽度,int(s[1]/(浮点(s[0])/浮点(宽度)))
如果ns[1]>高:
ns=(int(s[0]/(float(s[1])/float(HIGHT)),HIGHT)
i2=i.resize(ns)
bimg=[]
对于范围内的r(0,i2.大小[1],4):
直线=u“
lastCol=-1
对于范围内的c(0,i2.大小[0],2):
val=0
i=0
cavg=[0,0,0]
pc=0
对于范围(0,4)内的ci:
对于范围内的ri(0,3,如果ci=2:
ci-=2
ri=3
#检索像素数据
如果c+ci0:
p=映射(λx:255-x,p)
elif alpha==0:
p=字母颜色
其他:
p=(0,0,0)
#检查截止值,如果通过,则添加到unicode值
卢马=(0.2126*浮点数(p[0])+0.7152*浮点数(p[1])+0.0722*浮点数(p[2]))
pv=总和(p[:3])
如果luma>截止:
val+=1不要将stdout
设置为您的文件,而是将其保留为默认值,并在打印时使用文件I/O操作写入文件
# open the file
f = open('I put my path here to .txt file','a')
for u in convert(args.file,doColor=not args.nocolor, renderIRC=args.irc, cutoff=args.c, size=args.s, invert=args.invert, alphaColor=alphaColor):
toWrite = u.encode('utf-8')
# write to the file
f.write(toWrite)
print toWrite
# close the file
f.close()
嗯,对S.O.来说这不是一个很好的问题…很简单:只需使用两个命令-一个用于控制台,一个用于文件!仅供参考,Windows 10控制台。非常感谢!我终于可以打印到终端和文本文件了!非常爱你:*