在另一个 python 脚本中调用 python 脚本时出现奇怪的错误

发布于 2024-11-08 07:57:35 字数 5878 浏览 1 评论 0原文

在另一个 python 脚本(script1)中调用 python 脚本(script2)时出现 IOError。

如果单独调用,脚本 2 运行良好,但是,如果我从脚本 1 中调用它,则会收到以下错误。

C:\>C:\Python32\python.exe R:\Scripts\BatchAging.py
Traceback (most recent call last):
  File "R:\Scripts\DeleteAgingFiles.py", line 59, in <module>
    hdlr = logging.FileHandler(log)
  File "C:\Python32\lib\logging\__init__.py", line 965, in __init__
    StreamHandler.__init__(self, self._open())
  File "C:\Python32\lib\logging\__init__.py", line 984, in _open
    stream = open(self.baseFilename, self.mode)
IOError: [Errno 22] Invalid argument: 'C:\\ C:\\cleanup.log'

脚本 1(由自动调度程序调用)

# AGING CLEANUP SCRIPT
# BUILT & TESTED WITH PYTHON 3.2

import os,errno,sys,time,logging
from datetime import datetime
from subprocess import call

st = time.time()

#
# CONFIG  STATIC VARS
# Remeber to escape backslash characters with an additional backslash.
#

pythonBin = 'C:\\Python32\\python.exe'      #LOCATION OF PYTHON BIN
script = 'R:\\Scripts\\DeleteAgingFiles.py'  #LOCATION OF AGING FILE CLEANUP SCRIPT
dirs = ['C:\\backup']           # DIRECTORY TO PRUNE
batchLog = 'C:\\batchLog.log'
log = 'C:\\cleanup.log'         # LOCATION OF THE LOG FILE.  (THIS WILL BE AUTO GENERATED)
maxAgeInDays = 14           # MAX AGE OF  FILES\DIRS IN DAYS
mtime = True            # USE MTIME INSTEAD OF CTIME


# ##################################################
#
#       DO NOT MODIFY ANYTHING BELOW THIS LINE.
#
# ##################################################

logger = logging.getLogger('batchCleanup')
hdlr = logging.FileHandler(batchLog)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr) 
logger.setLevel(logging.INFO)

logger.info("[STARTING BATCH CLEANUP] [SCRIPT=%s] [DIRS=%s] [MAXAGE=%s] [MTIME = %s]" % (sys.argv[0],dirs,maxAgeInDays,str(mtime)))

if mtime == True:
    mtswitch = '-m'
else:
    mtswitch = ''

for dir in dirs:
    print([pythonBin,script,'-d ' + dir,'-l ' + log,'-a ' + str(maxAgeInDays),mtswitch])
    try:
        call([pythonBin,script,'-d ' + dir,'-l ' + log,'-a ' + str(maxAgeInDays),mtswitch])

    except:
        logger.error("[BATCH] Exception while processing directory: %s ]" % (dir))
        logger.error("[BATCH] Unexpected error: %s" % sys.exc_info()[1])

rt = time.time() - st

logger.info("[BATCH CLEANUP COMPLETE] [TOTAL RUN TIME: %s second(s)" % rt)

脚本 2(由脚本 1 调用)

# AGING FILE CLEANUP SCRIPT
# BUILT & TESTED WITH PYTHON 3.2

import os,errno,sys,argparse,time,logging
from datetime import datetime
from shutil import rmtree
st = time.time()

#
#  EXAMPLE  USAGE:
#
# This cript can use either dynamic vars (imput args) or static vars.
# To change this behavior, change the commenting below.
#
#     Dynamic vars:
#       C:\Python32\python.exe R:\Scripts\DeleteAgingFiles.py -d C:\backup -l C:\aging.log -a 14 -m
#
#     Static vars:
#       C:\Python32\python.exe R:\Scripts\DeleteAgingFiles.py
#

#
# INPUT ARGUMENT PROCESSING
#

parser = argparse.ArgumentParser(description='Prune aging files from directory.')
parser.add_argument('-d','--dir',dest='dir',help='Full path to folder to be pruned',required=True)
parser.add_argument('-l','--log', dest='log',help='Full path to log file',required=True)
parser.add_argument('-a','--age', dest='age',type=int,help='Maximum age of files',required=True)
parser.add_argument('-m','--mtime',dest='mtime',action='store_true',default=False,help="Use mtime instead of ctime")

args = parser.parse_args()

dir = args.dir
log = args.log
maxAgeInDays = args.age
mtime = args.mtime

print(log)

#
# CONFIG  STATIC VARS
# Remeber to escape backslash characters with an additional backslash.
#

# dir = 'C:\\backup'            # DIRECTORY TO PRUNE
# log = 'C:\\cleanup.log'           # LOCATION OF THE LOG FILE.  (THIS WILL BE AUTO GENERATED)
# maxAgeInDays = 14         # MAX AGE OF FILES\DIRS IN DAYS
# mtime = False             # USE MTIME INSTEAD OF CTIME


# ##################################################
#
#       DO NOT MODIFY ANYTHING BELOW THIS LINE.
#
# ##################################################

logger = logging.getLogger('cleanup')
hdlr = logging.FileHandler(log)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr) 
logger.setLevel(logging.INFO)

logger.info("[STARTING CLEANUP] [SCRIPT=%s] [DIR=%s] [MAXAGE=%s] [MTIME = %s]" % (sys.argv[0],dir,maxAgeInDays,str(mtime)))

os.chdir(dir)
files = os.listdir(dir)

for file in files:
    if file == '.' or file == '..': continue
    path = dir + os.sep + file
    global objType

    if mtime == True:
        ts = datetime.fromtimestamp(os.stat(path).st_mtime)
    else:
        ts = datetime.fromtimestamp(os.stat(path).st_ctime)

    global objType

    if os.path.isdir(path):
        objType = 'DIRECTORY'

    else:
        objType = 'FILE'

    age = datetime.now() - ts
    if age.days > maxAgeInDays :
        try: 

            if os.path.isdir(path):
                rmtree(path)

            else:
                os.remove(path)

        except OSError as exc:
            if exc.errno == errno.EACCES:
                logger.warning("[PERMISSION DENIED] [%s] [%s] [AGE: %s day(s)]" % (objType,path,age.days))

            else:
                logger.error("Exception while processing: %s [%s] [AGE: %s day(s)]" % (path,objType,age.days))
                logger.error("Unexpected error: %s" % sys.exc_info()[1])

        else:
            logger.info("[DELETED %s] [%s] [AGE: %s day(s)]" % (objType,path,age.days))

    else :
        logger.info("[IGNORED %s] [%s] [AGE: %s day(s)]" % (objType,path,age.days))

rt = time.time() - st

logger.info("[CLEANUP COMPLETE] [TOTAL RUN TIME: %s second(s)" % rt)

I am getting an IOError when calling a python script(script2) within another python script(script1).

Script 2 runs fine if called stand alone, however, if I call it from within script one, i get the following error.

C:\>C:\Python32\python.exe R:\Scripts\BatchAging.py
Traceback (most recent call last):
  File "R:\Scripts\DeleteAgingFiles.py", line 59, in <module>
    hdlr = logging.FileHandler(log)
  File "C:\Python32\lib\logging\__init__.py", line 965, in __init__
    StreamHandler.__init__(self, self._open())
  File "C:\Python32\lib\logging\__init__.py", line 984, in _open
    stream = open(self.baseFilename, self.mode)
IOError: [Errno 22] Invalid argument: 'C:\\ C:\\cleanup.log'

Script 1 (Called by auto scheduler)

# AGING CLEANUP SCRIPT
# BUILT & TESTED WITH PYTHON 3.2

import os,errno,sys,time,logging
from datetime import datetime
from subprocess import call

st = time.time()

#
# CONFIG  STATIC VARS
# Remeber to escape backslash characters with an additional backslash.
#

pythonBin = 'C:\\Python32\\python.exe'      #LOCATION OF PYTHON BIN
script = 'R:\\Scripts\\DeleteAgingFiles.py'  #LOCATION OF AGING FILE CLEANUP SCRIPT
dirs = ['C:\\backup']           # DIRECTORY TO PRUNE
batchLog = 'C:\\batchLog.log'
log = 'C:\\cleanup.log'         # LOCATION OF THE LOG FILE.  (THIS WILL BE AUTO GENERATED)
maxAgeInDays = 14           # MAX AGE OF  FILES\DIRS IN DAYS
mtime = True            # USE MTIME INSTEAD OF CTIME


# ##################################################
#
#       DO NOT MODIFY ANYTHING BELOW THIS LINE.
#
# ##################################################

logger = logging.getLogger('batchCleanup')
hdlr = logging.FileHandler(batchLog)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr) 
logger.setLevel(logging.INFO)

logger.info("[STARTING BATCH CLEANUP] [SCRIPT=%s] [DIRS=%s] [MAXAGE=%s] [MTIME = %s]" % (sys.argv[0],dirs,maxAgeInDays,str(mtime)))

if mtime == True:
    mtswitch = '-m'
else:
    mtswitch = ''

for dir in dirs:
    print([pythonBin,script,'-d ' + dir,'-l ' + log,'-a ' + str(maxAgeInDays),mtswitch])
    try:
        call([pythonBin,script,'-d ' + dir,'-l ' + log,'-a ' + str(maxAgeInDays),mtswitch])

    except:
        logger.error("[BATCH] Exception while processing directory: %s ]" % (dir))
        logger.error("[BATCH] Unexpected error: %s" % sys.exc_info()[1])

rt = time.time() - st

logger.info("[BATCH CLEANUP COMPLETE] [TOTAL RUN TIME: %s second(s)" % rt)

Script 2 (called by script 1)

# AGING FILE CLEANUP SCRIPT
# BUILT & TESTED WITH PYTHON 3.2

import os,errno,sys,argparse,time,logging
from datetime import datetime
from shutil import rmtree
st = time.time()

#
#  EXAMPLE  USAGE:
#
# This cript can use either dynamic vars (imput args) or static vars.
# To change this behavior, change the commenting below.
#
#     Dynamic vars:
#       C:\Python32\python.exe R:\Scripts\DeleteAgingFiles.py -d C:\backup -l C:\aging.log -a 14 -m
#
#     Static vars:
#       C:\Python32\python.exe R:\Scripts\DeleteAgingFiles.py
#

#
# INPUT ARGUMENT PROCESSING
#

parser = argparse.ArgumentParser(description='Prune aging files from directory.')
parser.add_argument('-d','--dir',dest='dir',help='Full path to folder to be pruned',required=True)
parser.add_argument('-l','--log', dest='log',help='Full path to log file',required=True)
parser.add_argument('-a','--age', dest='age',type=int,help='Maximum age of files',required=True)
parser.add_argument('-m','--mtime',dest='mtime',action='store_true',default=False,help="Use mtime instead of ctime")

args = parser.parse_args()

dir = args.dir
log = args.log
maxAgeInDays = args.age
mtime = args.mtime

print(log)

#
# CONFIG  STATIC VARS
# Remeber to escape backslash characters with an additional backslash.
#

# dir = 'C:\\backup'            # DIRECTORY TO PRUNE
# log = 'C:\\cleanup.log'           # LOCATION OF THE LOG FILE.  (THIS WILL BE AUTO GENERATED)
# maxAgeInDays = 14         # MAX AGE OF FILES\DIRS IN DAYS
# mtime = False             # USE MTIME INSTEAD OF CTIME


# ##################################################
#
#       DO NOT MODIFY ANYTHING BELOW THIS LINE.
#
# ##################################################

logger = logging.getLogger('cleanup')
hdlr = logging.FileHandler(log)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr) 
logger.setLevel(logging.INFO)

logger.info("[STARTING CLEANUP] [SCRIPT=%s] [DIR=%s] [MAXAGE=%s] [MTIME = %s]" % (sys.argv[0],dir,maxAgeInDays,str(mtime)))

os.chdir(dir)
files = os.listdir(dir)

for file in files:
    if file == '.' or file == '..': continue
    path = dir + os.sep + file
    global objType

    if mtime == True:
        ts = datetime.fromtimestamp(os.stat(path).st_mtime)
    else:
        ts = datetime.fromtimestamp(os.stat(path).st_ctime)

    global objType

    if os.path.isdir(path):
        objType = 'DIRECTORY'

    else:
        objType = 'FILE'

    age = datetime.now() - ts
    if age.days > maxAgeInDays :
        try: 

            if os.path.isdir(path):
                rmtree(path)

            else:
                os.remove(path)

        except OSError as exc:
            if exc.errno == errno.EACCES:
                logger.warning("[PERMISSION DENIED] [%s] [%s] [AGE: %s day(s)]" % (objType,path,age.days))

            else:
                logger.error("Exception while processing: %s [%s] [AGE: %s day(s)]" % (path,objType,age.days))
                logger.error("Unexpected error: %s" % sys.exc_info()[1])

        else:
            logger.info("[DELETED %s] [%s] [AGE: %s day(s)]" % (objType,path,age.days))

    else :
        logger.info("[IGNORED %s] [%s] [AGE: %s day(s)]" % (objType,path,age.days))

rt = time.time() - st

logger.info("[CLEANUP COMPLETE] [TOTAL RUN TIME: %s second(s)" % rt)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

早茶月光 2024-11-15 07:57:35

更清洁的是导入脚本并运行其 main 方法:

import DeleteAgingFiles
DeleteAgingFiles.main()

向脚本添加 main 方法:

def main():
    # the main code goes here

if __name__ == "__main__":
    main()

Cleaner is to import the script and run its main method:

import DeleteAgingFiles
DeleteAgingFiles.main()

Adding a main method to your script:

def main():
    # the main code goes here

if __name__ == "__main__":
    main()
蓬勃野心 2024-11-15 07:57:35

我认为,这个问题的最佳解决方案是不要使用 call 来访问其他 python 脚本。相反,将其作为模块导入并直接调用其函数。

The best solution to this problem, is, I would think, don't use call to access the other python script. Instead, import it as a module and call its functions directly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文