I have a script that effectively does the following:
top_script.py:
os.system("bash_script.sh")
bash_script.sh
python3 child_script.py
child_script.py
# Actual work goes here
In VSCode, I love the integrated debugger, but when I follow their advice[1] when launching from the IDE, I get "ECONNREFUSED 127.0.0.1:5678".
When I execute the following from the integrated terminal in VSCode, it runs without the errors, but it doesn't stop on breakpoints in child_script.py.
python3 -m debugpy --listen 5678 top_script.py
How can I execute the top script first (either from the IDE or command line) and have breakpoints I attach in child_script.py be rendered in VSCode?
[1] https://code.visualstudio.com/docs/python/debugging
It's fairly simple. You can add a configuration to your launch.json file like the following:
{
"name": "MySubProcess",
"type": "python",
"request": "attach",
"processId": "${command:pickProcess}
}
Now start your python process separately (via a prompt, or however). This will generate a python subprocess. You can see this in Windows Task Manager (or also in MacOS Activity monitor, or in Linux a similar way).
In VSCode, then click Debug, (select your subprocess configuration: "MySubProcess" in our example above), and then choose the process which was just started. The debugger will then stop at the breakpoints in your subprocess code.
The problem is that by using os.system() the debugger doesn't know you started another Python interpreter that you care about. What you will need to do is attach to the second process. Details will vary depending on how you want to set this up, but you can look at https://code.visualstudio.com/docs/python/debugging#_local-script-debugging as a starting point.
I followed RexBarker's suggestion, but VSC always gave me an error of "Timed out waiting for debug server to connect". In order to find out the cause, the "log to file" was enabled in the Configuration like below,
{
"name": "MySubProcess",
"type": "python",
"request": "attach",
"processId": "${command:pickProcess}",
"logToFile": true
}
Then I could find the detailed error in the log file on the VSC host, which is located at ~/.local/share/code-server/extensions/ms-python.python-2021.5.926500501/debugpy.adapter-{pid}.log
It told me 'gdb' not found. After I installed gdb, it works as expected.
Related
I have a program that uploads videos to via the vimeo api. But everytime I click run, the program that runs is not the current one, its an old program, which I have now deleted and even deleted from recycle bin, yet everytime I run my vimeo code it runs a completely different program that shouldnt even exist its driving me crazy!
I've tried to adjust my setting file which currently looks like below.
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "internalConsole"
}
]
}
I suspect you have a script cached somewhere. To troubleshoot please do the following:
Restart VScode
Restart PC (if on windows 10 use shutdown/r /f /t 000 in cmd to force a full restart and avoid windows fast-boot saving anything.)
check what happens if you run the script manually via python your script and see what happens.
Comment if this doesn't help and add more info such as your OS and how you are running your script.
If you are importing any module like "import some_module" you could change it to "from some_module import *", or the specific function you want.
I have just installed VS Code and the Python extension, and I have not been able to get the debugger to work. Every time I try to use the debugger, it just skips over any breakpoints that I have set and runs the program like normal.
I am using VS Code on a Windows 10 PC with Python 3.7.3 and the Python extension installed. I followed the instructions here (https://code.visualstudio.com/docs/python/python-tutorial) to make a test folder called 'hello' in C:\python_work\hello and create a program called 'hello.py' inside that folder. hello.py is shown below. I tried using the debugger both by pressing the green arrow and by pressing F5, but neither seemed to make the debugger work properly. My 'launch.json' file is also shown below.
hello.py:
msg = "Hello World!"
print(msg) # Breakpoint
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": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"stopOnEntry": true
},
]
}
I expected the bottom bar to turn orange and the program to stop on the second line, allowing me to examine the local and global variables in the preview pane. Instead, the bottom bar stayed orange for 1/2 a second while the program ran as if I had pressed "Run Python File in Terminal," without stopping at the breakpoint. Please help!
Setting "justMyCode": false makes it stop at breakpoint:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Debug Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"stopOnEntry": true,
"justMyCode": false
},
]
}
If you're using a pytest-cov module you might also wanna have a look at pytest configuration settings note:
Note If you have the pytest-cov coverage module installed, VS Code doesn't stop at breakpoints while debugging because pytest-cov is using the same technique to access the source code being run. To prevent this behavior, include --no-cov in pytestArgs when debugging tests, for example by adding "env": {"PYTEST_ADDOPTS": "--no-cov"} to your debug configuration.
See an example configuration file (launch.json) below:
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Tests",
"type": "python",
"request": "test",
"console": "integratedTerminal",
"justMyCode": false,
"env": {"PYTEST_ADDOPTS": "--no-cov"}
}
]
}
I experienced the same behaviour and was able to solve it by installing the virtual environment of Python in the following way:
[MyProjectFolder] \ venv
by entering the command
python -m venv [MyProjectFolder]\venv
in the console.
VS Code seems to expect exactly that folder structure.
Before I had installed the venv-folder-structure directly in my projects-folder, i.e.
[MyProjectFolder] \ Scripts
[MyProjectFolder] \ Lib
[MyProjectFolder] \ Include
[MyProjectFolder] \ pyvenv.cfg
which did not work and caused exactly the described debug problems.
just as a reference: VS Code version 1.52.1 and Python 3.8.5
Downgrading from Python 3.9 to 3.8 worked for me.
VC Code 1.56.2 ignored breakpoints running Python 3.9 64-bit on Windows 10 version 20H2. Installing Python 3.8.10 64-bit fixed the problem. I just needed to select the Python 3.8.10 interpreter within VS code and it now recognizes breakpoints. No changes to the configuration file were needed, for example, I did not need "justMyCode": false
I realize this is an old question, but my google search lead me to it. Many of the previous answers no longer apply. So I'm posting this fix for others who land here in 2021 trying to use 3.9.
I had the same problem having upgraded from Python version 3.7 to version 3.9. I later found out that the old version was 32 bit, and the new version I upgraded to was 64 bit, which apparently caused the issues. Uninstalling the 64 bit version and installing the 32 bit version of Python 3.9 solved my problem, and I was then able to use the Visual Studio Code breakpoint functionality again.
For everyone coming here looking for a solution related to breakpoints in python unittests:
If not already done add a configuration file, i.e. launch.json, as described in the vscode python debugging tutorial.
For me the following configuration settings worked, whereby setting cwd (because of src and test folders) and purpose (see also here) were essential.
"version": "0.2.0",
"configurations": [
{
"name": "Python: Test Cases",
"type": "python",
"request": "launch",
"cwd": "${workspaceFolder}/afinad/src",
"purpose": [
"debug-test"
],
"console": "integratedTerminal",
}
]
Happy debugging!
I recently found out ( 5th May 2020) that using Python 3.9 as interpreter the breakpoints were not hitting. Install 3.8 and it will start working again.
My issue was that I was putting the breakpoint on the line of the function declaration itself, so the def foo(x): line, instead of putting the breakpoint on the first non-comment line inside of the function.
If the first line of your function is a comment, the debugger will assume you meant to place the breakpoint on the line of the function declaration and move your breakpoint back, so really make sure you aren't placing your breakpoint on a comment!
Another source of no-breakpoints-working is elevate:
try: # https://pypi.org/project/elevate/
from elevate import elevate
except ModuleNotFoundError: # install it if not found
subprocess.call([sys.executable, "-m", "pip", "install", 'elevate'])
finally:
from elevate import elevate
# require elevated permissions right away...
elevate()
The elevate() command restarts the program as a new (child) process, so the entire file becomes un-breakpoint-able. From the author:
On Windows, the new process’s standard streams are not attached to the parent, which is an inherent limitation of UAC.
In windows, to debug python applications in VS Code which need to be run as administrator, a work-around is this:
Close VS Code.
Right-click VS Code icon, choose "Run as Administrator."
Linux users could likely do the same with sudo code. Now the process will be spawned initially as administrator, so the call to elevate() does nothing and the whole file is debuggable.
Another source of debugger not stopping at breakpoint: an homonym file, from another directory, is open in VS Code.
In fact, VS Code can set breakpoints on any Python file, even outside of your Python project's directory; if the path of the file does not match the one in launch.json, "program": [your-file-name-here] entry, then breakpoints are not hit.
For example: copies of Python source files are located under dist/lib, the output of setuptools (run: python setup.py bdist_wheel to generate them).
If dist/lib is not excluded through .gitignore, then its contents shows up in the search results sidebar and can be click open by mistake.
Caveat: the above does not hold if the launch.json configuration has "program": "${file}".
I (re)downloaded VS Code again: https://code.visualstudio.com/
The breakpoint got to show up on hover and function with the Run and Debug for the python file I was working on.
Additionally, I had to solve a syntax error in my code before the debugger buttons (step over/in, etc) had to go through the code lines
I have been battling with this for the last hour, and it finally worked by renaming my python file from camelCase.py to snake_case.py
I am not very new to Python, fairly new to VSC (moved to MacOS recently) and very new to Ansible. I am trying to build a plugin to circumvent our weird jump host (long story and sad, so far). A very simple step would solve this, but, in trying to get where to put that step, I wanted to do a full debug of ansible-playbook python script and everything that comes with it.
I am on 1.29.1 Visual Studio Code, Ansible 2.7.0, Python 3.6.4 through anaconda.
What am I trying to do:
I have created a profile in launch.json:
{
"name": "Python: Ansible playbook",
"type": "python",
"request": "launch",
"program": "${file}",
"args": [
"--inventory=/full_path/inventory.ans",
"/full_path/test-playbook.yml"
],
}...
that enables me to launch debug. I have tried without any breakpoints - it goes to the same point as it does when I run it in command line.
Short explanation about the arguments: .ans file is an Ansible repository explicitly specified (to override default config) and the other is the actual playbook. Contents of both do not play a role, I tried arguments for my other scripts - they are accepted...
I have added:
Breakpoints at any point in the ansible-playbook file - while it stops there (paused on breakpoint in call stack window), I do not see any variables or anything in the left pane. Further, I have only options to pause, restart and stop debugging.
If I add an option to break on start, I have exactly the same behaviour.
I have downloaded PyCharm and did similar thing there and I have an option to go step by step, see variables and so on.
Any help/direction is appreciated.
If I try to debug my other Python scripts, it works as expected, I get yellow pointer and I can skip through steps. Main difference is that I do have a .py extension in my scripts and that I use very simple Object Oriented elements, not even close to what is in Ansible...
I've had a big problem with debugging in VSCODE lately. I have tried to fix it my self by searching the site and reinstalling some of my extensions.
Instead of showing my results in the debug console it writes the following output to my terminal:
cd /Users/AVFL/Documents/Programming ; env "PYTHONIOENCODING=UTF-8"
PYTHONUNBUFFERED=1" /usr/local/bin/python3
/Users/AVFL/.vscode/extensions/ms-python.python-2018.3.1/pythonFiles/PythonTools/visualstudio_py_launcher.py
/Users/AVFL/Documents/Programming 54323 34806ad9-833a-4524-8cd6-18ca4aa74f14 RedirectOutput,RedirectOutput
/Users/AVFL/Documents/Programming/Python/Projects/Entrepeneuring/employeeDatabase.py
and the results from my script show up below that. The results also show up in the debug console but I would like them to only show up there.
I am debugging with the Python: Current file. I have tried changing the console to none in the external and integrated terminal function, but I need those to be default.
What can I do to make it debug in the debug console when I use Python: Current File?
I've seen one post with this question but they changed the console to none and debug in the Python: Integrated Terminal instead of Current File
The problem occurred when I made a virtualenv in my folder.
Just go to your launch.json script and find thre attach part. Change the setting from integrated terminal to none. Should work :)
I've found the answer myself. Instead of changing the other configurations to print the info in the debug console I create a new Configuration with the name "Python: Current File" which I added as the fist configuration. I made the console "none" in this configuration and I deleted the other one. This solved my problem with out removing other vulnerable settings.
Setting "console": "None" in the launch.json is not valid in the latest versions of VS Code. Note, however, that you will still get the desired behavior, but VS Code will consider it an invalid setting. To make VS Code happy, set "console" to "internalConsole" to get the output to go to the Debug Console instead of to a Terminal, like this:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "internalConsole"
}
]
}
I am trying out Visual Studio Code, to learn Python.
I am writing a starter piece of code to just take an input from the user, say:
S = input("What's your name? ")
When I try to run this (Mac: Cmd + Shift + B) I see the task is running with no output. I have already configured the tasks.json file for output and arguments.
print("Hello, World!")
S = input("What's your name? ")
Do I need to configure some environment variables in Visual Studio Code?
Tasks are intended for building your application. Since Python is interpreted, you don't need to use tasks.json at all to run/debug your Python code. Use the launch.json instead. I am using Don Jayamanne's Python extension for debugging and have configured the launch.json as follows:
Open the Command Palette (Ctrl + Shift + P) and write the command:
start without debugging
Then select your Environment -> Click Python. This should create a launch.json file within a .vscode directory in the current directory.
Paste the following configuration json
{
"version": "0.2.0",
"configurations": [
{
"name": "Python",
"type": "python",
"request": "launch",
"stopOnEntry": true,
"pythonPath": "${config.python.pythonPath}",
"program": "${file}",
"debugOptions": [
"WaitOnAbnormalExit",
"WaitOnNormalExit",
"RedirectOutput"
],
"console": "integratedTerminal"
}
]}
Save the file, open your python script in the editor and 'start without debugging' again. This should launch an integrated terminal where you can give input as well as see the output.
Ctrl+Shift+d, then choose integrated terminal/console.
You could install the Python extension for Visual Studio Code from the Visual Studio Code market place.
Once done, use the "Python Console" debug option to run and debug your Python code. This will launch the terminal/command window allowing you to capture input, and you wouldn't need to configure the tasks.json file for this.
Python extension: https://marketplace.visualstudio.com/items?itemName=donjayamanne.python
When you click the debug option, it takes you to the debug console instead of an actual integrated terminal. This is because the debug console only shows your code is running smoothly, but it doesn't actually allow you to add input.
I have already tried Don's suggestion and sadly it doesn't work. What you said originally by configuring the .json file was correct. With Visual Studio Code , you can only "work with" your code on a
command line. Hopefully that gets changed in the future.
In vscode Terminal tab type:
python3 file_name.py
Using Visual Studio code 1.66.0 with Pylance and launch.json config on Windows 10x64
While all my code executed in the internal debugger, the INPUT code would not. I could not use the integrated terminal for input.
I applied the configuration by Keshan Nageswaran. I did, however, have to comment out, "pythonPath":
"${config.python.pythonPath}", as VSC came back with the alert, The Python path in your debug configuration is invalid.
That being said, I am extremely grateful for the config code. I was able to respond to the input in the integrated terminal. My input was visible in the integrated terminal and reflected in the internal debugger.
type your code in Interactive window e.g.
age = input('enter a num')
print(type(age))
then execute code.
Now it is waiting to you for enter a number as age. Enter a number in empty bar and up of your vscode window that is written "enter a num" under the it, and press Enter. As a result you can see bellow aswer in interactive window:
<class 'str'>
and as follow you can see testing your code
This helped me: instead of clicking on the "Run Code" option, click on "Run Python file", in the right corner.
February 2023 answer in 3 easy steps:
Install Code Runner.
Open Settings ( Ctrl + ,)
Search and tick the box for 'Code Runner: Run In Terminal' . DONE.