Windows10下运行高校Python脚本创建临时目录失败,报KeyError
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:
- Environment variable difference: Linux uses
USERto store the current username, but Windows usesUSERNAMEinstead. When the script tries to fetchos.environ['USER'], that key doesn't exist on your system, triggering theKeyError. - 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 likeC:\Users\<YourName>\AppData\Local\Tempfor 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-styleUSER.
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

