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

Windows10下运行高校Python脚本创建临时目录失败,报KeyError

Fixing the "KeyError" & Temporary Directory Issue on Windows 10

Hey there, let's break down what's going wrong here and fix it step by step.

First, let's zero in on the root of your error:

Traceback (most recent call last):
File "Calign.py", line 116, in
tmpbase = '/tmp/' + os.environ['USER'] + '_' + str(os.getpid())
File "C:\Python27\lib\os.py", line 425, in getitem
return self.data[key.upper()]
KeyError...

Why this happens

The script was clearly written with Linux/Unix systems in mind, not Windows—here are the two main mismatches:

  1. Environment variable difference: Linux uses USER to store the current username, but Windows uses USERNAME instead. When the script tries to fetch os.environ['USER'], that key doesn't exist on your system, triggering the KeyError.
  2. Temporary directory path mismatch: Windows doesn't have a /tmp/ directory by default. That path is standard on Linux, but Windows uses a system-specific path like C:\Users\<YourName>\AppData\Local\Temp for temporary files.

Solutions to fix this

Option 1: Cross-platform fix (best approach)

Update the script to work on both Windows and Linux by using Python's built-in tempfile module, which handles system-specific temp directories automatically, plus fallback logic for the username.

First, add this import at the top of the script (if it's not already there):

import tempfile

Then replace line 116 with this code (tailored for Python 2.7):

# Grab username with cross-platform fallback
username = os.environ.get('USER', os.environ.get('USERNAME', 'temp_user'))
# Create a unique temp directory using system's default temp location
tmpdir = tempfile.mkdtemp(prefix="{0}_".format(username))

This code:

  • Pulls the correct username variable for your OS, with a default if neither exists.
  • Creates a unique temporary directory in Windows' default temp folder, so you don't have to hardcode /tmp/.

Option 2: Windows-only quick fix

If you only need this script to run on Windows, you can modify the original line directly:

tmpbase = os.path.join(os.environ['TEMP'], os.environ['USERNAME'] + '_' + str(os.getpid()))
  • os.environ['TEMP'] fetches Windows' default temp directory path automatically.
  • os.environ['USERNAME'] uses your Windows username instead of the Linux-style USER.

Testing the fix

After making either change, run the script again—you shouldn't hit the KeyError anymore, and the script should successfully create its temporary directory without issues.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:16:32