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
Related
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"
}
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 have been giving VSCode a serious try after using PyCharm for many years. I am enjoying it, but there are some things I can't quite figure out. Here is something that I have done many times within PyCharm:
Run a file, say main.py, by Ctrl+Shift+F10 (runs selected code).
Inspect output.
Change supplemental_code.py.
Re-run main.py by Ctrl+F10 (notice the lack of "Shift". This re-runs last executed script).
In VSCode I only see a way to run the selected script. Is there any way to achieve the behavior I'm gotten accustomed to, but within VSCode?
In PyCharm:
Ctrl+Shift+F10: run the current file.
Shift+F10: run the file which you configured.
Shift+F9: debug the file which you configured.
In VSCode:
Run Python File in Terminal: run the current file.
Through click the top right green triangle or right-click in the file and select this command. It has no shortcut in default, but you can modify it by yourself. Equal to Ctrl+Shift+F10 in PyCharm.
There is no way to configure the file which Python File in Terminal command to execute. So that's impossible to get an equal effect like Shift+F10 in PyCharm.
But you can configure in the launch.json like this to get the equal effect like Shift+F9 in PyCharm:
from:
"program": "${file}", //means the current file.
to:
"program": "${workspaceFolder}/xxx/xxx.py", //specific way to the file you want to execute. ${workspaceFolder} means the path of the folder opened in VS 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
In Matlab and R, I can run a code and the console/terminal of MATLAB's editor and R-Studio will expose the session to me. In a way that I can access all the variables and results of my simulations from the console. I have found some solutions online, but I am not satisfied with them or they were not clear to me.
So here is the question:
How can I modify VS Code so that the code which I am running will have the same session in the terminal or change it to pythons currently running session?
ipython or jupyter seems to do this task. How can I do that in ipython/jupyter?
Let say if I have in my python p1.py the following line:
a=3
and I execute the above-mentioned line, after execution, I want to be able to input the following line in the terminal or console of VS Code and get a correct result:
b=a+10
Many thanks!
You can use Run Selection/Line in Python Terminal which will send the text to a Python REPL instance. If you're after changes in the REPL to be reflected in the editor then I'm afraid that support does not exist.
In USER SETTINGS I modified the following:
{
"jupyter.appendResults": true,
//"terminal.integrated.shell.windows": "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
"terminal.integrated.shell.windows": "C:\\Program Files\\Python36\\Scripts\\ipython.exe",
"[python]": {
}
}
Then I added this line:
{
"python.pythonPath": "run"
//"python.pythonPath": "C:\\Program Files\\Python36\\python.exe"
}
In the WORKSPACE SETTINGS of VS Code. After running a simple addition/subtraction test, I can access the variables in the ipython terminal.