如何在Visual Studio Code 2019中实现Python工作区变量自动保存?
Hey there! I totally get what you're going through—you want to run your Python scripts for ESRI products in VS Code 2019, then reuse the generated variables later without re-running the entire script, just like Spyder does. Let's break down the easiest ways to make this work:
1. Use the Python Interactive Window (Recommended)
This is the closest you'll get to Spyder's variable explorer workflow:
- Open your Python script in VS Code.
- To run the entire script and retain variables: Select the full script (or just the initial code block you need), then press
Shift+Enter(or right-click and choose "Run Selection/Line in Python Interactive Window"). - Once the code runs, all your variables stay alive in the interactive window's session. You can:
- Type directly into the interactive window to test code that uses those variables.
- Select any snippet from your script and hit
Shift+Enteragain to run it—this will automatically pull in the existing variables.
- Pro tip: Look for the tiny table icon in the interactive window to open the Variable Explorer, where you can view and manage your variables just like in Spyder.
2. Keep the Terminal Session Alive After Script Execution
If you prefer using the integrated terminal over the interactive window:
- Open the Run and Debug panel (
Ctrl+Shift+D). - Create a
launch.jsonfile (click "create a launch.json file" if you don't have one, then select your Python environment). - Replace the default configuration with this:
{ "name": "Python: Persist Session", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal", "stopAtEntry": false, "env": {"PYTHONUNBUFFERED": "1"}, "justMyCode": true }
- Run this configuration (click the green play button). After your script finishes, the terminal won't close—you can immediately type Python code into it to reference the variables from your script.
3. Save Variables Long-Term (For Restarting VS Code)
If you need to keep variables even after closing VS Code, use Python's pickle module to serialize them to a file:
- Add this code at the end of your script to save variables:
import pickle # Replace 'esri_variables.pkl' with your preferred filename with open('esri_variables.pkl', 'wb') as f: pickle.dump([layer_data, analysis_results, project_path], f) # List variables you want to save
- When you need to load them later, run:
import pickle with open('esri_variables.pkl', 'rb') as f: layer_data, analysis_results, project_path = pickle.load(f)
Just make sure your VS Code Python extension is up to date—older 2019 versions might have limited support for interactive window features.
内容的提问来源于stack exchange,提问作者bonnerrhea

