繁体   English   中英

将程序日志保存到文本文件中

[英]Save program logs into a text file

我想将程序日志(显示在屏幕中)保存到文本文件中,但在集成 def() 部分时遇到了困难。

到目前为止,我的 data_log 是(保存在文件中):

日期和时间:2021-12-21 16:05:50.927868

输入:[1、4、9、16、25]

递归:[[3, 5, 7, 9], [2, 2, 2], [0, 0], [0]]

在这方面,我想保存此查询末尾所述的程序日志,而不是我的 data_log 程序。 我是一名高中生。

这张图片显示了类似的概念:

user = input("Name:")

def shrink(numbers, return_list=[]):
    n1 = [(x, numbers[i + 1]) for i, x in enumerate(numbers) if i < len(numbers) - 1]
    n2 = [x[1] - x[0] for x in n1]

    return_list.append(n2)

    if (len(n2) > 1):
        return shrink(n2, return_list)
    else:
        return return_list

input_user = input("Enter data:")
b = input_user.split()
for num in range(len(b)):
    b[num] = int(b[num])
c = shrink(b)
print(c)

def sequence_identifier():
    from fractions import Fraction


    #3 Quadratic Sequence
    if len(c[0:len(c)]) >= 2:
        if c[1][:-1] == c[1][1:] and sum(c[1]) != 0 and len(c[1]) > 1:
            print('Sequence type: quadratic sequence')
            x = Fraction((c[1][0])/2)
            y = Fraction(c[0][0]-(x*3))
            z = Fraction(1 - (x + y))
            print('The general formula is: an^2 + bn + c')
            print('a:',str(x))
            print('b:',str(y))
            print('c:',str(z))
            print('Would you like to find an nth term?[Press 1]')
            Yes3 = int(input())
            if Yes3 == 1:
                while True:
                    nth3_1 = int(input('What is the nth term:'))
                    nthterm3_1 = ((x)*(nth3_1**2) + (y*nth3_1) + z)
                    print('The nth term is', nthterm3_1)
                    print('Would you like to try again?')
                    confirmloop3_1 = int(input('Press 1 to continue:'))
                    if confirmloop3_1 == 1: continue
                    else: break

sequence_identifier()

# I want to modify this:
with open(user, 'a+') as data_log:
    from datetime import datetime
    data_log.write(str('_'*100))
    data_log.write('\n')
    data_log.write('Date and Time: '+ str(datetime.now()))
    data_log.write('\n')
    data_log.write('Input: '+ str(b))
    data_log.write('\n')
    data_log.write('Recursion: '+ str(c))
    data_log.write('\n')
    data_log.close()

该程序的屏幕日志为:(斜体为输入)

姓名:拉尔夫

输入数据: 1 4 9 16 25

[[3, 5, 7, 9], [2, 2, 2], [0, 0], [0]]

序列类型:二次序列

一般公式为:an^2 + bn + c

一个:1

乙:0

c:0

您想找到第 n 个词吗?[按 1]

1

第 n 项是什么: 10

第 n 项是 100

你想再试一次吗?

按 1 继续: 2

您可以使用日志记录 package 并提供一些基本配置以将日志保存为所需格式

import logging

logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
logging.warning('This will get logged to a file')

您可以根据您正在编写的日志使用 logging.error、logging.info、logging.debug。 所有这些日志都将存储在文件名中提到的文件中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM