#python #logging #ioerror #invalid-argument
#python #ведение журнала #ioerror #недопустимый аргумент
Вопрос:
Я получаю ошибку IOError при вызове скрипта python (script2) в другом скрипте python (script1).
Скрипт 2 работает нормально, если вызывается автономно, однако, если я вызываю его из скрипта one, я получаю следующую ошибку.
C:>C:Python32python.exe R:ScriptsBatchAging.py
Traceback (most recent call last):
File "R:ScriptsDeleteAgingFiles.py", line 59, in <module>
hdlr = logging.FileHandler(log)
File "C:Python32liblogging__init__.py", line 965, in __init__
StreamHandler.__init__(self, self._open())
File "C:Python32liblogging__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 amp; 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 FILESDIRS 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 amp; 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:Python32python.exe R:ScriptsDeleteAgingFiles.py -d C:backup -l C:aging.log -a 14 -m
#
# Static vars:
# C:Python32python.exe R:ScriptsDeleteAgingFiles.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 FILESDIRS 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)
Ответ №1:
Очиститель заключается в импорте скрипта и запуске его основного метода:
import DeleteAgingFiles
DeleteAgingFiles.main()
Добавление метода main в ваш скрипт:
def main():
# the main code goes here
if __name__ == "__main__":
main()
Ответ №2:
Я бы подумал, что лучшим решением этой проблемы является не использовать call для доступа к другому скрипту Python. Вместо этого импортируйте его как модуль и вызывайте его функции напрямую.