【ABAQUS 二次开发笔记】Python 报错收集和解决方法

1. 运行报错,找不到本地文件及模块、自定义模块

1.1 Example:

$/home/tops/bin/python xxx.py
Traceback (most recent call last):
  File "xxx.py", line 22, in <module>
    from xxx.xxx import xxx
ImportError: No module named xxx.xxx

1.2 Reason

import模块默认会从PYTHONPATH里寻找,但是当前要import的文件路径不在PYTHONPATH里(PYTHONPATH是python搜索模块的路径,python解释器会根据PYTHONPATH下的路径寻找各个模块)

1.3 Solution

python文件中添加路径:

  import sys
  modulePath='自定义模块的文件夹路径'
  sys.path.append(modulePath)

将项目根目录加入到sys.path模块中,在每个目录下的__init__.py中加入上述代码,这样,在该目录下的py文件通过引入__init__.py之后,就不用在每个文件里写入上述代码了。

#########################################################
#将根目录加入sys.path中,解决命令行找不到包的问题
import sys
import os
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
#########################################################

2. Python TypeError: 'newline' is an invalid keyword argument for this function

2.1 Example

写一个存为csv文件的代码

 with open(outputFile, 'w', newline='') as csvfile:
     writer = csv.writer(csvfile)
     for item in sortsim:
         writer.writerow([item[0], item[1], item[2]])

出现问题了:

Traceback (most recent call last):
  File "/data/ml/shan-als.py", line 54, in <module>
    with open(outputFile, 'w', newline='') as csvfile:
TypeError: 'newline' is an invalid keyword argument for this function

2.2 Reason

python 版本的原因,python2和python3的open()函数参数不一样。py2用’wb’,py3可以用newline=’’。

2.3 Solution

加版本判断:

    import sys
    if sys.version >= '3':
        with open(outputFile, 'w', newline='') as csvfile:
            writer = csv.writer(csvfile)
            for item in sortsim:
                writer.writerow([item[0], item[1], item[2]])
    else:
        with open(outputFile, 'wb') as csvfile:
            writer = csv.writer(csvfile)
            for item in sortsim:
                writer.writerow([item[0], item[1], item[2]])

3. AttributeError: XXX instance has no attribute 'xxx'

3.1 Problem

调用某个模块时报AttributeError: GetData instance has no attribute 'data_config'
img

3.2 Solution

4. Python:'xxx' object is not callable

4.1 Reason

当出现报错 ‘xxx’ is not callable的时候,通常都是函数名重用或者变量名重用。
当出现这个错误时查看报错语句中用到的变量名或者函数名在其他语句中是否重用。

当显示 is not callable 时,表示 Python 代码调用了一个不能被调用的变量或者对象,有可能是可能是调用了错误的函数或者变量(即函数和变量重名),使得调用函数时,系统会误认为这是在调用变量,造成错误。

callable对象是指一个后边可以加()的对象,比如函数,所以这种异常肯定是某对象多加了(),比如:把一个变量用了函数名来命名,结果再调这个函数的时候就会报这个异常。

4.2 Solution

检查、修改变量名

5. python-logging日志写入文件(直接可用,简单易行,最简单的输出写入文件)

import logging
def logger_config(log_path,logging_name):
    '''
    配置log
    :param log_path: 输出log路径
    :param logging_name: 记录中name,可随意
    :return:
    '''
    '''
    logger是日志对象,handler是流处理器,console是控制台输出(没有console也可以,将不会在控制台输出,会在日志文件中输出)
    '''
    # 获取logger对象,取名
    logger = logging.getLogger(logging_name)
    # 输出DEBUG及以上级别的信息,针对所有输出的第一层过滤
    logger.setLevel(level=logging.DEBUG)
    # 获取文件日志句柄并设置日志级别,第二层过滤
    handler = logging.FileHandler(log_path, encoding='UTF-8')
    handler.setLevel(logging.INFO)
    # 生成并设置文件日志格式
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    # console相当于控制台输出,handler文件输出。获取流句柄并设置日志级别,第二层过滤
    console = logging.StreamHandler()
    console.setLevel(logging.DEBUG)
    # 为logger对象添加句柄
    logger.addHandler(handler)
    logger.addHandler(console)
    return logger
 
if __name__ == "__main__":
    logger = logger_config(log_path='log.txt', logging_name='据说名字长一点容易被人记住')
    logger.info("info")
    logger.error("error")
    logger.debug("debug")
    logger.warning("warning")
    print('print和logger输出是有差别的!')
posted @ 2023-01-07 22:58  FE-有限元鹰  阅读(1617)  评论(0编辑  收藏  举报