From what I found in the community, there are two options to extend the Python search path with further libraries.
.env
e.g. PYTHONPATH="C:\path\to\a;C:\path\to\b"
launch.json
e.g.
{
// 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": {
"PYTHONPATH": "${workspaceFolder}/lib"
}
}
]
}
After searching again for this topic on multiple days, I did not yet find any clear solution for that.
Some things work as expected, others don't. To be clear, it might be just a wrong understanding of the
concepts. Since I found multipe threads on the topic, but almost just the same answers, which did not
yet work out for me. There are multiple threads aroung that stuff, so I assume some general interest for a clarification.
Currently I tested exlusively each option. Using both things in parallel is somehow not comfortable,
also since the capabilities are different. .env does not support pre-defined variables,
lauch.json, does. So I tested .env without settings in launch.json and no .env file + settings in launch.json.
I use VS Code 1.75.1, but it was the case also for multiple previous version.
Anaconda Python3 with different virtual environments.
What I see is the following, when using the options in VS Code:
yes --> extending the PYHTONPATH worked as expected
no --> extending the PYHTONPATH dir NOT worked as expected
Run option
.env setting
launch.json setting
Run Python file in terminal
no
no
Run in interactive Window
yes
no
Debug via F5
yes
yes
"Debug Python File" (*)
yes
no
(*) Debug via "Debug Python File" in Drop-Down of Run Symbol above right of the editor window
I assumed both debug options should be the same, but I have sometimes situations, where starting Debug via F5 works as expected, but using the Debug Symbol reports an error.
Not clear, why both debug options behave differently.
No idea, why running Python terminal, does ignore path settings completely.
In general more detailed information about the ideas behind both optios, would be very helpful. Why there is a difference for just running code in the terminal and debugging. The concept of launch configurations I know from other IDEs and it makes a lot of sense to me. Is there a way define such conigurations hiarchically, so only changes have to be added for lower levels and the rest can be kept common.
Setting all environment stuff on OS/command shell level, is possible via system/user variables. But I thought, that VS Code is doing that specifically for each workspace/project.
What am I doing wrong? What do have I missed during setup of VS Code? Or where do I not yet understand the concecept/workflow correctly.
I expected to control the library path settings for each workspace seperately. Potenitally in just one place (one configuration setting) in the workspace area (.env or launch.jason, or what ever other way)
Any help/comment is appreciated, thanks a lot,
Mike
For the questions raised in your article, if you're only interested in debugging a Python script, the simplest way is to select the down-arrow next to the run button on the editor and select Debug Python File.
If you're looking to debug a web application using Flask, Django or FastAPI, the Python extension provides dynamically created debug configurations based on your project structure under the Show all automatic debug configurations option, through the Run and Debug view(f5).
You can read document basic-debugging for more detials.
I expected to control the library path settings for each workspace
seperately.
I suggest you using virtual environment. This makes it easier for you to manage your library.
In addition, if you want to import the package in the specified location, you can use env in the launch.json file:
"env": {
"PYTHONPATH": "path/to/your/package"
}
Related
I keep getting this error. Other have faced this issue and have asked this question already and I have tried every single solution that was posted but I still get the error.
Things I have tried to solve this problem:
Uninstalled and reinstalled python and VScode.
ctrl+shift+p and added python interpreter to path.
manually entered path in launch.json. "python": "C:\Users\saura\AppData\Local\Programs\Python\Python310\python.exe"
Not sure what more can I do.
I messed around with conda, julia, anaconda without having much knowledge about it and I have a feeling that might be the issue. I did however uninstalled everything regarding conda, julia, anaconda.
If anyone has any idea what could I do, I would really appreciate it.
Here's the screenshot of json file. I do not see anything wrong with it yet.
Post the content of your launch.json file so that people can take a look at it.
You Configuration Should Look Like This:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Base",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"justMyCode": true,
"args": [],
"python": "path-to-python"
}
]
}
From menu bar of VS Code (Run), go to Open Configurations and paste above content after replacing path-to-python with yours.
Make sure you are using edited debug configuration when launching the debug for script.
Look in the lower right corner of your interface, where you are prompted to choose a python interpreter.
You should just click there or use Ctrl+Shift+P to open the command palette and choose Python:Select Interpreter, then choose the appropriate python interpreter.
I know you have tried many ways for this. But here's the problem, you haven't selected a python interpreter for vscode. If none of the methods work, try reinstalling the python extension.
Also, if the "python" configuration in your launch.json is the same as you showed in your question. then it is wrong, you should use / or \\. like this:
// Example 1
"python": "C:/Users/saura/AppData/Local/Programs/Python/Python310/python.exe"
// Example 2
"python": "C:\\Users\\saura\\AppData\\Local\Programs\\Python\\Python310\\python.exe"
I really like streamlit as an environment for research. Mixing a notebook/dashboard-like output I can design quickly with pure code for its definition (no cells etc.) as well as the ability to influence my code through widgets while it runs is a game changer.
For this purpose, I was looking for a way to run or even debug a streamlit application, since the tutorials only show it being started via the commandline:
streamlit run code.py
Is there a way to do either running or debugging from an IDE?
I found a way to at least run the code from the IDE (PyCharm in my case). The streamlit run code.py command can directly be called from your IDE. (The streamlit run code.py command actually calls python -m streamlit.cli run code.py, which was the former solution to run from the IDE.)
The -m streamlit run goes into the interpreter options field of the Run/Debug Configuration (this is supported by Streamlit, so has guarantees to not be broken in the future1), the code.py goes into the Script path field as expected. In past versions, it was also working to use -m streamlit.cli run in the interpreter options field of the Run/Debug Configuration, but this option might break in the future.
Unfortunately, debugging that way does not seem to work since the parameters appended by PyCharm are passed to streamlit instead of the pydev debugger.
Edit: Just found a way to debug your own scripts. Instead of debugging your script, you debug the streamlit.cli module which runs your script. To do so, you need to change from Script path: to Module name: in the top-most field (there is a slightly hidden dropdown box there...). Then you can insert streamlit.cli into the field. As the parameters, you now add run code.py into the Parameters: field of the Run/Debug Configuration.
EDIT: adding #sismo 's comment
If your script needs to be run with some args you can easily add them as
run main.py -- --option1 val1 --option2 val2
Note the first -- with blank: it is needed to stop streamlit argument parsing and pass to main.py argument parsing.
1 https://discuss.streamlit.io/t/run-streamlit-from-pycharm/21624/3
If you're a VS Code user, you can debug your Streamlit app by adding the following configuration to your launch.json file:
{
"name": "Python:Streamlit",
"type": "python",
"request": "launch",
"module": "streamlit",
"args": [
"run",
"${file}",
"--server.port",
"SPECIFY_YOUR_OWN_PORT_NUMBER_HERE" ]
}
Specifying the port number allows you to launch the app on a fixed port number each time you run your debug script.
Once you've updated your launch.json file, you need to navigate to the Run tab on the left gutter of the VS code app and tell it which Python config it should use to debug the app:
Selecting Debug config for python interpreter
Thanks to git-steb for pointing me to the solution!
I've come up with an alternative solution which allows you to use PyCharm debugging in a natural way. Simply set up a run script (which I call run.py which looks like this:
from streamlit import bootstrap
real_script = 'main_script.py'
bootstrap.run(real_script, f'run.py {real_script}', [], {})
and set that up as a normal Python run configuration in PyCharm.
Cannot comment so I have to put this as an answer.
An addition to #Ben's answer (module debugging part):
if your script needs to be run with some args you can easily add them as
run main.py -- --option1 val1 --option2 val2
Note the first -- with blank: it is needed to stop streamlit argument parsing and pass to main.py argument parsing
With some modification to #aiwa answer - This worked for me in the VS code version - 1.58
{
"configurations": [
{
"name": "Python:Streamlit",
"type": "python",
"request": "launch",
"module": "streamlit.cli",
"args": [
"run",
"${file}"
],
}
]
}
Aug, 12, 2022:
Please update your pip and streamlit versions. Sometime, it is mandatory to update all both version.
pip install pip --upgrade
pip install --upgrade streamlit
Open Pycharm Editor and go to the Edit Configuration file as mentioned below in picture. Do not clear streamlit in my dropdown box. Click on dropdown box.
Run/Debug Configurations:
You have to change three directories remember that script path.
1) You can obtain script path by typing which streamlit in terminal and paste the path in script path.
2) click on working directory and give directory of your python file which contain streamlit.
3) in Paramaters: give python file name like app.py with run.
Alongside other solutions, another easy and quick solution is using pdb library.
For instance;
st.dataframe(df)
import pdb; pdb.set_trace()
st.bar_chart(df)
When you run code, your IDE (or even command line) will stop at the 'set trace' point and the command line show you something like that:
(Pdb)>
In that case, you can call your variables and process them on the command line. For instance:
For other options of PDB library please see: https://docs.python.org/3/library/pdb.html
I want to debug a python module in vscode to save time and help me figure out what's going on with the code. But I'm having two problems (I'll focus more on the 1st issue for this post) that seem like they're related to me not using launch.json correctly and I would like to know what's going wrong. I'm working on a Mac.
My module is called __main__. The full absolute path to it would be ~/Code/APPRES-483/cqs/update-query-definition/__main__.py (__main__.py is a script, but it seems the module is called __main__ as well).
There's a virtualenv at ~/Code/APPRES-483/venv-cqs/ that I'm using. I opened up a VSCode window inside of ~/Code/APPRES-483/cqs/update-query-definition/.
Right now my launch.json file looks like this.
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Module",
// "python":"~/Code/APPRES-483/venv-cqs/bin/python",
"type": "python",
"request": "launch",
"module": "__main__",
"pythonArgs":[
"-v",
"--file-to-write", "~/Code/APPRES-483/LOCAL-query-definition.yml"
],
},
]
}
The first problem is that I can't actually set the python interpreter path in launch.json. I have my virtualenv active inside of VSCode (i.e. I see the prefix for venv-cqs that I intend to see).
If I open up a terminal and put ~/Code/APPRES-483/venv-cqs/bin/python, that correctly opens up the python terminal/executable inside of venv-cqs/bin. If I add a line like "python":"~/Code/APPRES-483/venv-cqs/bin/python", I get the message saying "the python path in your debug configuration is invalid."
I tried to follow https://stackoverflow.com/a/66885651/6432861 instructions to use the Python: Select Interpreter command. I'm getting some weird behavior.
If I try to browse finder/files to find the python executable in venv-cqs/bin/, once I double click on the file it doesn't actually get made into the python interpreter for vs code. If I hover my mouse in the bottom left, I'm still seeing the address of my default python installation in /usr/local/bin or wherever it is.
But if I copy and paste ~/Code/APPRES-483/venv-cqs/bin/python rather than trying to browse for files, that successfully changes the python interpreter and I can see that at the bottom left of my screen.
The only way that the code avoids these errors is if I don't have a python field in the configuration for launch.json. I know that's not how it's supposed to be so... I want to know what's going wrong.
The second problem I'm having is with pythonArgs. But I'll try to make another post about it since this is already long enough.
First, you may set
"python.defaultInterpreterPath": "~/Code/APPRES-483/venv-cqs/bin/python",
in User Settings.json to specify python interpreter. If it doesn't work and VS Code still shows default python installation as python interpreter in bottom-left corner, deleting the user data folders $HOME/Library/Application Support/Code and .~/.vscode can reset VS Code.
Second, the setting python defaults to the interpreter selected for your workspace, so once you have selected the venv-cqs as python interpreter, debug would use it by default and if you insist that, set
"python": "${command:python.interpreterPath}"
I am trying to debug a simple Python program that reads a CSV and writes a new one in VS Code. When I set a breakpoint, it gets skipped. I am able to use breakpoint() and get the basic Python debugger, but I'd prefer to be able to use the VS Code debugger. I found this SO post and this documentation, but neither resolved the issue. I am on Windows, Python version 3.9.1. I am not an experienced Python developer, so it's very possible I'm missing something obvious, but I have done my fair share of .NET development.
UPDATE 1: launch.json and code
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,
"justMyCode": false
}
]
}
For the code, I've set breakpoints all over the place trying to get it to work, but here is my main.py. I've tried a breakpoint on the line h.get_approvers():
import adp
import hierarchy
import expensify
import sys
h = hierarchy.Hierarchy()
h.get_approvers()
UPDATE 2: Terminal output when debugging
Loading personal and system profiles took 664ms.
PS C:\Users\...\OneDrive - ZoomInfo\Dev\Sandbox\PyTest> & C:/Python39/python.exe "c:/Users/.../OneDrive - ZoomInfo/Dev/Sandbox/PyTest/main.py"
Hello world
PS C:\Users\...\OneDrive - ZoomInfo\Dev\Sandbox\PyTest>
Update
The issue has been closed and I have received confirmation that it was related to the Python version 3.9.3 (64 bit).
https://github.com/microsoft/vscode-python/issues/15865
Original Post
This has been driving me nuts and needs further investigation, but what I noticed
Python 3.9.3 64 bit >> skips breakpoints
and
Python 3.9.2 64 bit >> works as expected
I have reproduced this multiple times just to ensure that I wasn't just solving a problem with a simple un-/reinstall.
I have raised an issue for this and I'll update this reply as soon as I find the proper root cause, but for now this solves the problem at my end...although not to my satisfaction.
https://github.com/microsoft/vscode-python/issues/15865
I noticed that in the terminal information you provided, the only paths used are "python.exe" and the file "main.py" path.
In VS Code, the debugging function of Python code is provided by Python extensions. Therefore, when debugging python scripts, it will use "python interpreter" (python.exe), "python extension" (.vscode\extensions\ms -python.python-2021.1.502429796\pythonFiles\lib\python\debugpy), and "python script" (.py file).
When I click the green run button in the upper right corner of VS Code, the path displayed on the VS Code terminal is only python.exe and the ".py" file: Run the code and it will not stay at the breakpoint.
When I click F5 or the "Start Debugging" button: Debug code it will stay at the breakpoint.
If it still doesn't work, please try to reinstall the Python extension and reload VS Code.
Reference: Python debugging in Visual Studio Code.
When executing "Run Selection/Line in Python Terminal" command in VSCode, terminal's current working directory is the workspace root directory. How can we set current directory of terminal to the current file's directory when running the selection/line?
In "User Settings", use the search bar to look for "python.terminal.executeInFileDir" and set (=) its value to "true" instead of "false".
Update following release 2019.10.44104
Following release 2019.10.44104 of the VS Code python extension, you can now set the python.dataScience.notebookFileRoot to ${fileDirname} to directly start the python interactive window in the directory of the file you're running.
Note that the root directory will not change if you then run code from another file unless you interrupt/restart the kernel (or close VS Code). On this aspect, see the following comment and the corresponding github issue.
For the Python Interactive Window, the setting you're looking for is python.dataScience.notebookFileRoot. However, as explained in this answer to a similar question,
Always opening on the file location (without having to set notebookFileRoot to an absolute path per folder) is not supported via the notebookFileRoot setting. The VSCode variables such as ${fileDirname} are specific to task and debug configuration files (launch.json and task.json).
See also the associated github issue.
As indicated, you can still set this setting to a specific absolute path, which might be enough if you're mainly working on a single project at a time.
Alternatively, you could also add the following code at the top of your script/notebook:
import os
os.chdir('absolute-path-to-workingDir')
I used the option Run -> Add Configuration (or Open configuration, if available)
This will open your current 'launch.json' file.
Now you may add this line to the configuration wanted (in my case was Python):
"cwd": "${fileDirname}"
This line will make VSCode to run your stuff in the same folder as the file is being executed.
You can get more details in this link:
https://code.visualstudio.com/docs/editor/variables-reference
Here is my full json file (just for reference):
{
// 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",
"cwd": "${fileDirname}"
}
]
}
you need to go to file/preferences/user settings and click the "{}" icon at the top right of the window. After that, put this setting in: "terminal.integrated.cwd": "C:\\Users\\myUser\\", and after that wherever your terminal's directory happens to be. This answer is not the most inaccurate cause im still a noob myself at using vscode so if someone more experienced with it could reply to this thread it would be great.
There is no straightforward way to achieve this yet. In search for a better solution, I have a workaround with the Terminal Here extension in the VScode Marketplace. This extension allows you to open an integrated terminal in the current file's directory. This extension combined with a few more steps and you should get the desired behavior.
Once the extension is installed, make sure your file window is in focus, and press ctrl+shift+p and execute Terminal Here: Create Terminal. This will create a new terminal in the file's directory.
Type python in the terminal to launch the Python interpreter.
Now, position the cursor on the line you wish to execute and press ctrl+shift+p and execute Terminal: Run selected text in active terminal. This will run that line of code in the open python interpreter.
The first two steps are required only for the first time you run a code selection in the Python interpreter in the current file's directory. All subsequent selections can be run with the third step. To make things quicker, you could attach custom keybindings to the first and last steps.
This options will help you.
File->Preferences->Settings.
Add or edit the below setting.
terminal.integrated.shell.windows": ""
From the next terminal it will be reflected.
And add .profile to your default shell and add default path to it.
More information at: https://code.visualstudio.com/docs/editor/integrated-terminal
this issue is answered here. The solution is to config the launch.json file in .vscode folder