简体   繁体   English

如何将变量传递给导入的脚本

[英]How to pass variable to imported script

I have few scripts where I multiplay some code and I started to do refractoring. 我有几个脚本,我多重播放一些代码,我开始做refractoring。 Below is the code which: 以下是代码:

1) Create directory in the same place where the script is named log 1)在脚本命名为log的相同位置创建目录

2) Puts information into log/file_name.log 2)将信息放入log / file_name.log中

Below is the code: 以下是代码:

    # Get path where script is
pathABSofScript = ""
if platform.system() == "Linux":
    pathABSofScript = str(os.path.realpath(__file__).rsplit('/', 1)[0]) + "/"
else:
    print("Unknown operating system")
    exit(1)

if debug == "on":
    print("Absolute path for script: {0}".format(pathABSofScript))

# Create directory
directories = ['log']
for directory in directories:
    try:
        os.makedirs("{0}{1}".format(pathABSofScript, directory))
    except FileExistsError as ex:
        pass
    except Exception as ex:
        logger.error("An exception of typ {0} occurred in function {2}. Arguments:\n{1!r} exiting.".format(type(ex).__name__, ex.args, sys._getframe(2).f_code.co_name))
        exit(1)

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh = handlers.RotatingFileHandler('{0}/log/scriptName.log'.format(pathABSofScript), maxBytes=1000000,
                                  backupCount=10)
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.info("Started")
As every my script has the same code I would like to create directory lib and call this code logger.py.

I have created directory structure as below: 我创建了如下目录结构:

scripts/
    lib/
        logger.py
    someScript/
        someScript.py

Previously in someScript directory script created log directory and then logged informations in someScript/log/someScript.log file. 以前在someScript目录脚本中创建了日志目录,然后在someScript / log / someScript.log文件中记录了信息。

When I have moved code to logger.py file making an import inside someScrip.py 当我将代码移动到logger.py文件中时,在someScrip.py中进行导入

sys.path.insert(0, '/me01/apps/onetick/apps/config-test/lib')
import logger
from logger import logger

the created log directory is inside lib/ directory instead of someScript/ - how to change that? 创建的日志目录在lib /目录下而不是someScript / - 如何更改? I have tried to pass variable in someScript.py: 我试图在someScript.py中传递变量:

logger.pathABSofScript = "someScript/"

but it didn't worked. 但它没有奏效。

How to pass variable to logger.py while importing it inside someScript.py? 如何在someScript.py中导入变量时将变量传递给logger.py?

similar answer is here: Pass Variable On Import Basically, you have to create another folder, named "my_config" with __init__.py script in it. 类似的答案在这里: 导入时传递变量基本上,您必须创建另一个名为“my_config”的文件夹,其中包含__init__.py脚本。 So the structure of your project will be: 所以你的项目结构将是:

scripts/
    my_config/
        __init__.py
    lib/
        logger.py
    someScript/
        someScript.py

Then you have to put that code in my_config/__init__.py script: 然后你必须将该代码放在my_config/__init__.py脚本中:

PATH_TO_MY_SOURCE   = '/default/path'

Next, edit your lib/logger: 接下来,编辑您的lib / logger:

import my_config
PATH_TO_MY_SOURCE = my_config.PATH_TO_MY_SOURCE
...

Finally, in someScript.py: 最后,在someScript.py中:

import my_config
import os
my_config.PATH_TO_MY_SOURCE = os.path.dirname(os.path.realpath(__file__))
from logger import logger
...

Thanks @alex-b for sharing his idea. 谢谢@ alex-b分享他的想法。 I have found another solution for that: 我找到了另一个解决方案:

my logger.py looks like this: 我的logger.py看起来像这样:

import logging
import logging.handlers as handlers
import sys
import os
# IT IS NOT WORKING WITHOUT THIS LINE BELOW, DUNNO WHY
logger = None


def create_logger(path, file_name):
    global logger
    try:
        os.makedirs("{0}log".format(path))
    except FileExistsError as ex:
        pass
    except Exception as ex:
        logger.error("An exception of typ {0} occurred in function {2}. Arguments:\n{1!r} exiting.".format(
            type(ex).__name__, ex.args, sys._getframe(2).f_code.co_name))
        exit(1)
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh = handlers.RotatingFileHandler('{0}log/{1}'.format(path, file_name), maxBytes=1000000,
                                      backupCount=10)
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    logger.info("Started")


def info(msg):
    try:
        if isinstance(msg, str):
            logger.info(msg)
    except Exception as ex:
        logger.error("An exception of typ {0} occurred in function {2}. Arguments:\n{1!r} exiting."
                     .format(type(ex).__name__, ex.args, sys._getframe(2).f_code.co_name))
        exit(1)


def debug(msg):
    try:
        if isinstance(msg, str):
            logger.debug(msg)
    except Exception as ex:
        logger.error("An exception of typ {0} occurred in function {2}. Arguments:\n{1!r} exiting."
                     .format(type(ex).__name__, ex.args, sys._getframe(2).f_code.co_name))
        exit(1)


def warning(msg):
    try:
        if isinstance(msg, str):
            logger.warning(msg)
    except Exception as ex:
        logger.error("An exception of typ {0} occurred in function {2}. Arguments:\n{1!r} exiting."
                     .format(type(ex).__name__, ex.args, sys._getframe(2).f_code.co_name))
        exit(1)


def error(msg):
    try:
        if isinstance(msg, str):
            logger.error(msg)
    except Exception as ex:
        logger.error("An exception of typ {0} occurred in function {2}. Arguments:\n{1!r} exiting."
                     .format(type(ex).__name__, ex.args, sys._getframe(2).f_code.co_name))
        exit(1)

And I'm creating in my someScript.py 我在someScript.py中创建

# pathABSofScript is gathered from someScript.py itself
logger.create_logger(pathABSofScript, "refresh.log")
logger.info("IT works!")
logger.warning("Warning test.")

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

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