You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取logging配置文件触发OSError[Errno22]无效参数错误求助

Fixing OSError: [Errno 22] Invalid Argument with Python logging FileConfig on Windows

Let's break down exactly why you're hitting this error and walk through how to fix it quickly. The core issue here ties to how Windows-style file paths (with backslashes) are parsed when using logging.config.fileConfig.

What's Causing the Error

When you pass your Windows log path (like D:\home\site\wwwroot\App_data\jobs\triggered\Logs\ISS-20240520.txt) via the defaults parameter, the logging module uses ast.literal_eval to parse the args tuple from your config file. Since backslashes act as escape characters in Python strings, sequences like \L (from \Logs) aren't valid escape sequences—this confuses the file handler and throws the "invalid argument" error when trying to open the log file.

Also, there's a small readability issue in your script where you reassign the current_directory variable to the full log file path. It doesn't break functionality, but renaming it will make the code easier to follow.

Step-by-Step Solutions

1. Fix Path Escaping for Windows

Update your script to pass a path that won't be misinterpreted by the config parser. You have two simple options:

def _init_log():
    currentTime = datetime.now().strftime('%Y%m%d')
    fileName = f"ISS-{currentTime}.txt"  # Use f-strings for cleaner syntax
    working_dir = os.getcwd()  # Rename to avoid variable overlap
    log_dir = os.path.join(working_dir, 'Logs')
    
    # Create log directory (add exist_ok=True to avoid errors if it already exists)
    os.makedirs(log_dir, exist_ok=True)
    
    # Option 1: Convert backslashes to forward slashes (Python accepts these on Windows)
    log_file_path = os.path.join(log_dir, fileName).replace('\\', '/')
    # Option 2: Escape backslashes (double them up)
    # log_file_path = os.path.join(log_dir, fileName).replace('\\', '\\\\')
    
    logging.config.fileConfig(
        'logging.config', 
        defaults={'logfile': log_file_path}, 
        disable_existing_loggers=False
    )
    
    logger.info(f"Current working directory is: {working_dir}")
    logger.info(f"Real home directory is: {str(Path.home())}")

2. Clean Up Your logging.config File

Your config has two minor issues that don't cause the current error but can lead to unexpected log output:

  • Remove the single quotes around your formatter format values—logging will treat them as part of the log message otherwise:
    [formatter_simple]
    format=%(asctime)s [%(levelname)s] %(message)s
    datefmt=%Y/%m/%d %H:%M:%S
    [formatter_complex]
    format=%(asctime)s %(process)s %(processName)s [%(levelname)s] %(message)s
    datefmt=%Y/%m/%d %H:%M:%S
    
  • Make sure you've imported logging.handlers at the top of your script—without this, you'll get a "No module named handlers" error when using TimedRotatingFileHandler:
    import logging.handlers
    

3. Verify Parent Directory Access

Double-check that the parent path of your Logs folder (like D:\home\site\wwwroot\App_data\jobs\triggered) exists and your script has write permissions for it. If the parent path is missing, os.makedirs will fail unless you pass exist_ok=True (which we added in step 1).

Why This Works

By converting backslashes to forward slashes (or escaping them), we ensure that ast.literal_eval parses the path correctly without interpreting backslashes as invalid escape sequences. This lets the TimedRotatingFileHandler resolve the file path properly on Windows.

内容的提问来源于stack exchange,提问作者P113305A009D8M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:43:28