Setting Environment Variables for VSCode Debug session - visual-studio-code

I must be missing something very obvious here, but I cannot seem to get this to work.
I want to set an environment variable FOO to be available in the VSCode debug sessions started on the current file by hitting the Debug button in the top right corner
This one: .
I tried setting the env dictionary in the launch.json file like so:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"justMyCode": true,
"env": {
"FOO": "BAR"
}
}
]
}
But when I try to read the variable in my code, is get a KeyError since the variable hasn't been set.
import os
print(os.environ["FOO"])
yields this:
Traceback (most recent call last):
File ".../save_model.py", line 74, in <module>
print(os.environ["FOO"])
File ".../lib/python3.10/os.py", line 679, in __getitem__
raise KeyError(key) from None
KeyError: 'FOO'

Related

Change default terminal in VS Code to cmd

When I open VS Code, the default terminal is PowerShell and the default path is PS E:\Research\GM\Articles\Modularity\Covariance network\Graph theory\Metric basics\Consensus clustering\clustering_programs_5_2.
Q1: How could I change the default path in PowerShell to C:\Users<UserName>? (red line below)
Q2: How could I change the default terminal from PowerShell to cmd? (yellow circle below)
#############################################################################
I followed Geeky's method which worked well. However, the default path is still E:\Research\GM\Articles\Modularity\Covariance network\Graph theory\Metric basics\Consensus clustering\clustering_programs_5_2 rather than something like C:\Users<UserName>:
Press Ctrl + Shift + P. Type "def" and the default terminal selection option pops.
Click on it and select your preferred terminal
Alternatively, add this in your settings.json file
"terminal.integrated.defaultProfile.windows": "Command Prompt",
If the following code exists already in your settings.json file or else add the following code also
"terminal.integrated.profiles.windows": {
"PowerShell": {
"source": "PowerShell",
"icon": "terminal-powershell",
"path": "C:\\windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
},
"Command Prompt": {
"path": ["${env:windir}\\Sysnative\\cmd.exe", "${env:windir}\\System32\\cmd.exe"],
"args": [],
"icon": "terminal-cmd"
},
}

Unable to use environment variables in VS Code launch configuration

I have the following in my workspace settings.json file:
"terminal.integrated.env.osx": {
"AUTH_TOKEN": "secret_XXXXXX"
}
However, when trying to pass this via a launch command (defined in launch.json):
{
"name": "Example: Query",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/examples/query.py",
"args": [ "${env:AUTH_TOKEN}" ]
}
The resulting command contains an empty string for the argument:
/usr/bin/env /.../.venv/bin/python /.../debugpy/launcher 58644 -- /.../examples/query.py ""
However, if I print the variable from within the script, it is set properly.
I believe there is an ordering issue, such that the launch.json commands are generated before the terminal environment is set up - resulting in empty vars. Any ideas how to propagate the env value to the command line?
Update: I have also tried using a .env file for the variables (rather than settings.json), but the result is the same.
Try using "env" in launch.json...
{
"name": "Example: Query",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/examples/query.py",
"args": ["${AUTH_TOKEN}"], // using var from env on args
"env": {
"AUTH_TOKEN": "XXXX",
"ENV2" : "XXX"
}
}
you can use envs from file too
{
// ...
"args": ["${AUTH_TOKEN}"],
"envFile": "${workspaceFolder}/local.env",
}
You can create a .env file, and then put the variable in there, and read it from the environmental variables in the program instead of it being an argument.

VS Code No Module Found Error - Need help running PySpark code locally

I've been trying to switch over from PyCharm to VS Code full time, and while I've figured out most things, I'm having a hell of a time trying to run Spark jobs locally (OS X). As far as I can tell I have set up the same configuration (virtualenv and environment variables) as I had working on PyCharm. Here's the configuration I've got on VS Code (defined in launch.json):
{
"name": "Python: spark sql query (local)",
"type": "python",
"request": "launch",
"program": "${workspaceRoot}/scripts/my_script.py",
"console": "integratedTerminal",
"cwd": "${fileDirname}",
"args": [
.
.
.
],
"terminal.integrated.env.osx": {
"SPARK_HOME": "/usr/local/spark-3.1.2-bin-hadoop3.2"
},
"env": {
"PYTHONUNBUFFERED": "1",
"APP_NAME": "Local Script",
"LOGFILE": "output.log",
"SPARK_HOME": "/usr/local/spark-3.1.2-bin-hadoop3.2",
"JAVA_HOME": "/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/"
}
},
When I run this I just get ModuleNotFound errors even though I haven't changed any other piece of code from what was working in PyCharm. Any ideas for me to try?
Edit:
Traceback (most recent call last):
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/runpy.py", line 193, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/runpy.py", line 86, in _run_code
exec(code, run_globals)
File "/Users/evan***/.vscode/extensions/ms-python.python-2021.9.1191016588/pythonFiles/lib/python/debugpy/__main__.py", line 45, in <module>
cli.main()
File "/Users/evan***/.vscode/extensions/ms-python.python-2021.9.1191016588/pythonFiles/lib/python/debugpy/../debugpy/server/cli.py", line 444, in main
run()
File "/Users/evan***/.vscode/extensions/ms-python.python-2021.9.1191016588/pythonFiles/lib/python/debugpy/../debugpy/server/cli.py", line 285, in run_file
runpy.run_path(target_as_str, run_name=compat.force_str("__main__"))
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/runpy.py", line 263, in run_path
return _run_module_code(code, init_globals, run_name,
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/runpy.py", line 96, in _run_module_code
_run_code(code, mod_globals, init_globals,
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/runpy.py", line 86, in _run_code
exec(code, run_globals)
File "/Users/evan***/px_seed_model/scripts/sql_query.py", line 10, in <module>
from model import SparkModel
ModuleNotFoundError: No module named 'model'
The answer to this was to add PYTHONPATH to the env dict:
"env": {
"PYTHONUNBUFFERED": "1",
"APP_NAME": "Local Script",
"LOGFILE": "output.log",
"SPARK_HOME": "/usr/local/spark-3.1.2-bin-hadoop3.2",
"JAVA_HOME": "/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/",
"PYTHONPATH": "/path/to/project/root:$PYTHONPATH"
}
I believe this is equivalent to checking the box Add content roots to PYTHONPATH in PyCharm.

errors: -undefined reference to `_imp__GetStockObject#4' and undefined reference to `_imp__SetBkMode#8'

i wrote a code in visual studio code in windows10 in c++ to get simple window but unable to build and run
all the files used to debug are provided like task.json,launch.json and cpp-properties.json
plz tell me how to make windows project in visual studio code.
Errors are
> Executing task: g++ -g -lgdi32 main.cpp <
C:\Users\abhi\AppData\Local\Temp\cc0d0bc2.o: In function `WinMain#16':
C:\Users\abhi\Desktop\abs/main.cpp:38: undefined reference to `_imp__GetStockObject#4'
C:\Users\abhi\AppData\Local\Temp\cc0d0bc2.o: In function `Z10WindowProcP6HWND__jjl#16':
C:\Users\abhi\Desktop\abs/main.cpp:91: undefined reference to `_imp__SetBkMode#8'
collect2.exe: error: ld returned 1 exit status
The terminal process terminated with exit code: 1
main.cpp
#include <windows.h>
#include <tchar.h>
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam);
// Listing OFWIN_1
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
WNDCLASSEX WindowClass; // Structure to hold our window's attributes
static LPCTSTR szAppName { _T("OFWin") }; // Define window class name
HWND hWnd; // Window handle
MSG msg; // Windows message structure
WindowClass.cbSize = sizeof(WNDCLASSEX); // Set structure size
// Redraw the window if the size changes
WindowClass.style = CS_HREDRAW | CS_VREDRAW;
// Define the message handling function
WindowClass.lpfnWndProc = WindowProc;
WindowClass.cbClsExtra = 0; // No extra bytes after the window class
WindowClass.cbWndExtra = 0; // structure or the window instance
WindowClass.hInstance = hInstance; // Application instance handle
// Set default application icon
WindowClass.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
// Set window cursor to be the standard arrow
WindowClass.hCursor = LoadCursor(nullptr, IDC_ARROW);
// Set gray brush for background color
WindowClass.hbrBackground = static_cast<HBRUSH>(GetStockObject(GRAY_BRUSH));
WindowClass.lpszMenuName = nullptr; // No menu
WindowClass.lpszClassName = szAppName; // Set class name
WindowClass.hIconSm = nullptr; // Default small icon
// Now register our window class
RegisterClassEx(&WindowClass);
// Now we can create the window
hWnd = CreateWindow(
szAppName, // the window class name
_T("A Basic Window the Hard Way"), // The window title
WS_OVERLAPPEDWINDOW, // Window style as overlapped
CW_USEDEFAULT, // Default screen position of upper left
CW_USEDEFAULT, // corner of our window as x,y.
CW_USEDEFAULT, // Default window size width ...
CW_USEDEFAULT, // ... and height
nullptr, // No parent window
nullptr, // No menu
hInstance, // Program Instance handle
nullptr // No window creation data
);
ShowWindow(hWnd, nCmdShow); // Display the window
UpdateWindow(hWnd); // Redraw window client area
// The message loop
while (GetMessage(&msg, nullptr, 0, 0) == TRUE) // Get any messages
{
TranslateMessage(&msg); // Translate the message
DispatchMessage(&msg); // Dispatch the message
}
return static_cast<int>(msg.wParam); // End, so return to Windows
}
// Listing OFWIN_2
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message,
WPARAM wParam, LPARAM lParam)
{
switch (message) // Process selected messages
{
case WM_PAINT: // Message is to redraw the window
HDC hDC;
PAINTSTRUCT PaintSt; // Structure defining area to be drawn
hDC = BeginPaint(hWnd, &PaintSt) ; // Prepare to draw the window
// Get upper left and lower right of client area
RECT aRect; // A working rectangle
GetClientRect(hWnd, &aRect);
SetBkMode(hDC, TRANSPARENT); // Set text background mode
// Now draw the text in the window client area
DrawText(
hDC, // Device context handle
_T("But, soft! What light through yonder window breaks?"),
-1, // Indicate null terminated string
&aRect, // Rectangle in which text is to be drawn
DT_SINGLELINE | // Text format - single line
DT_CENTER | // - centered in the line
DT_VCENTER); // - line centered in aRect
EndPaint(hWnd, &PaintSt); // Terminate window redraw operation
return 0;
case WM_DESTROY: // Window is being destroyed
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
task.json
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "echo",
"type": "shell",
"command": "g++ -g main.cpp",
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
launch.json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/a.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"miDebuggerPath": "C:\\Program Files (x86)\\mingw-w64\\i686-8.1.0-posix-dwarf-rt_v6-rev0\\mingw32\\bin\\gdb.exe",
"preLaunchTask": "echo",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
cpp properties.json
{
"configurations": [
{
"name": "Win32",
"includePath": [
"C:\\Program Files (x86)\\mingw-w64\\i686-8.1.0-posix-dwarf-rt_v6-rev0\\mingw32\\lib\\gcc\\i686-w64-mingw32\\8.1.0\\include\\c++"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"windowsSdkVersion": "8.1",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "clang-x64",
"compilerPath": "C:\\Program Files (x86)\\mingw-w64\\i686-8.1.0-posix-dwarf-rt_v6-rev0\\mingw32\\bin\\gcc.exe"
}
],
"version": 4
}
You are using Visual Studio Code, but this question isn't really about VSCode, since the problem can be reproduced by running your first command at a command prompt (Windows cmd.exe or Cygwin bash):
> g++ -g -lgdi32 main.cpp
(errors as above)
Since you're trying to build a Windows program using MinGW gcc, you need to pass the -mwindows option:
> g++ -g -mwindows main.cpp
(works)
> ./a.exe
(runs)
Add the -mwindows to your tasks.json command and it should work from within VSCode too.

how to pass multiple args to vscode task command?

in tasks.json I am using the "args" property to specify the arguments to pass to "command":"gulp". But when I run the task in vscode, only the first argument is being passed to gulp.
I want to run a gulp task against a single file. In gulpfile.js I am using the process.argv array to retrieve the command line arguments. So, on the command line I enter "gulp copy3 --file abc.js" and the copy3 task is run. The code then reads the argv array to get the name of the file being copied.
this code works from the command line. But does not work when I run it as a task in vscode. How to do that?
the gulpfile.js code:
gulp.task('copy3', function( )
{
console.log(process.argv) ;
let pattern = '*.js' ;
// single file to copy
if (( process.argv.length >= 5 ) && ( process.argv[3] == '--file' ))
{
let fileName = process.argv[4] ;
pattern = fileName ;
}
console.log('pattern:' + pattern ) ;
return gulp.src(pattern).pipe(gulp.dest('dev'));
}) ;
the tasks.json file
{
"version": "2.0.0",
"tasks": [
{
"taskName": "copy3",
"command": "gulp",
"args": [ "copy3", "--file", "${fileBasename}" ],
"problemMatcher": []
}
]
}
Here is the terminal output:
[10:52:57] Using gulpfile C:\vscTest\rpgproj\gulpfile.js
[10:52:57] Starting 'copy3'...
[ 'C:\\Program Files\\nodejs\\node.exe',
'C:\\vscTest\\rpgproj\\node_modules\\gulp\\bin\\gulp.js',
'copy3' ]
pattern:*.js
[10:52:57] Finished 'copy3' after 16 ms
thanks,
I made a couple of small changes, try:
{
"label": "Tasks: copy3",
"type": "shell",
"command": "gulp",
"args": [ "copy3", "--file", "${fileBasename}" ],
"problemMatcher": []
}
and your entire code works perfectly. Make sure to reload vscode after modifying the tasks.json.
VSCode appears to have a built-in gulp extension. This seems to scan your gulpfile for tasks and list them for you. It also seems to ignore the args option.
The workaround is to use the full path to gulp as the command e.g. ./node_modules/.bin/gulp to bypass it.