zoukankan      html  css  js  c++  java
  • 调用其他python脚本文件里面的类和方法


    问题描述:

    自己编写了若干个Python脚本。

    在testC.py里面需要调用testA.py和testB.py里面的若干类和方法。要怎么办?

    需要都打包、安装,再去调用吗? 其实不必那么麻烦。


    这里有个前提,testA.py,  testB.py,  testC.py在同级目录下。

    如果不在同级目录,后面会补充介绍如何把路径包含过来。

    #  testA.py
    # -*- coding: utf-8 -*-
    
    class testA:
        def testA1():
            print("----testA1")
    
    def testA2(str):
        print("testA2---: " + str)
    # testB.py
    # -*- coding: utf-8 -*-
    
    def testB():
        print("this is testB")
    # testC.py
    
    import logging
    from testA import *
    from testB import *
    
    logging.basicConfig(level=logging.INFO, filename='mylog.log')
    logging.info('Starting program')
    
    # 这个logging仅仅为了掩饰日志记录功能,和这里讨论的主题无关 logging.info(
    "test testA.py")

    # 调用里面的类 testa
    = testA testa.testA1()
    # 调用里面的方法 testA2(
    "How are you?") logging.info("test testB.py") testB() logging.info('Ending program')

    这里有3个文件(testA.py, testB.py, testC.py)。

    在testC.py里面调用另外连个.py脚本的方法就是 import 模块脚本的全部内容。

    from testA import *
    from testB import *

    函数调用语法细节,请参看testC.py里面的代码。

    遗留问题:

    如果不在当前路径怎么办?

    用sys模块,将路径添加进来即可。

    例如,我这里就把testA.py放在了当前目录的today文件夹下面。把testB.py放在了父级目录(上一级目录)的yesterday文件夹下面。

    import sys
    sys.path.append(r'./today')
    sys.path.append(r'./../yesterday')
    from testA import *
    from testB import *
  • 相关阅读:
    编译java蛋疼的一小时
    最简单的Java Applet程序
    枚举任意进程内核对象句柄的方法
    RvmTranslator7.3.2
    PipeCAD
    Open CASCADE Technology 7.5.0 released
    IsoAlgo 环路处理
    OpenCASCADE STEP Color
    RvmTranslator 3D PDF in Ubuntu
    IsoAlgo Symbols
  • 原文地址:https://www.cnblogs.com/music-liang/p/11863023.html
Copyright © 2011-2022 走看看