Running Streamlit based app as a package ( - python-3.x

Apologies is this question is not clear enough - let me know and I can provide further details.
I've packaged up a Streamlit based app for a personal project. I've successfully deployed it on TestPyPi. I can install the package on a new environment/ machine - however am unsure how to actually 'run' (or launch) it there?
All of the pre-reqs are installing correctly using the following....
pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple interactive-charts-testJan2022b
However once installed if I use >>> from interactive_charts import run_me (which is a .py file that contains the following:)
import sys
from streamlit import cli as stcli
sys.argv = ["streamlit", "run", "basic_app_4.py"]
sys.exit(stcli.main())
The following is returned...
Usage: streamlit run [OPTIONS] TARGET [ARGS]...
Error: Invalid value: File does not exist: basic_app_4.py
Incidentally, I've included a hello_world.py file, which simply prints "Hello world". This works expected i.e. from interactive_charts import hello_world
I guess this is something to do with the relative path of where the package is installed locally i.e. where thebasioc_app_4.py is physically located; and how that's represented in the sys.argv variable? (as when I navigate to where hello_world.py is located in the terminal and then execute the command it works correctly.
I'm just not sure how I can tell it to use the physical location of the installed folder on the local users' machine?
Any ideas or work arounds would be gratefully received.
Any and all suggestions are welcome. TIA

Related

How to install splunkclient for Windows

I am trying to connect to my splunk server via Python on my WIndows laptop.
I downloaded splunklib and splunk-sdk. However, when I run
import splunklib.client as client
I get an error of
ModuleNotFoundError: No module named 'splunklib.client'; 'splunklib' is not a package
Any ideas on why this is occurring and suggestions on to how to fix this or the best way to access Splunk via Python?
Did you properly install the splunk-sdk? You would normally use something like pip to install it.
pip install splunk-sdk
Alternatively, you can install it into the PYTHONPATH
Refer to
https://dev.splunk.com/enterprise/docs/python/sdk-python/gettingstartedpython/installsdkpython/
Windows requires a manual setup of the SDK.
Download the Splunk Software Development Kit for Python as a zip file.
Unzip the zip file into the same directory as your program source.
Add the following line to your source code before import splunklib.client as client:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "splunk-sdk-python-master"))
Another option is to unzip the sdk to another folder and specify the absolute path in the sys.path.insert().

Import module from other directory in Python 3

I know this question has been asked thousands of times, but I still don't get the correct answer and stumble upon the same problem always.
I have the following file:
application/app/__init__.py
Here, I have some variable, let it be x.
Then, I have another file here:
application/tests/test_1.py
In test_1.py I do this:
from app import x
And, being in the application folder, I run:
python3 tests/test_1.py
But the following error happens:
ModuleNotFoundError: No module named 'app'
One solution that works is, inside test_1.py, add:
import sys
sys.path.append('../')
from app import db
Then if I do:
cd tests
python3 test_1.py
It works perfectly, but I don't want that sys.path.append and also I would like to do
python3 tests/test_1.py
Another solution is to explicitly modify the PYTHONPATH environment variable, but again, I wouldn't like to do this. Isn't there a clean solution to this problem?
Do not manually "hack" the sys.path. This is a bad practice "quick fix" that you've probably learned from stackoverflow answers.
Python looks for imports in either the site-packages folder or in the PYTHONPATH. The easiest way to get your local folder into the site-packages is using
pip install --editable path/to/myfolder
You only need a setup.py in your program "myfolder" with the following contents
from setuptools import setup
setup(name='myfolder")
The name "myfolder" is only important in case you want to uninstall it. But eventually this will create a symlink of your myfolder in the environments site-packages, and you can continue editing as before. But your program works "as if installed".
This is way more flexible than changing the PYTHONPATH.
As for the other comment:
When `application' is linked to site-packages and thereby recognized via sys.path,
from app import x
is an absolute import, since 'app' is a folder inside the top level folder 'application'.

How can I run a Flask application

The Flask official website says that we can run a Flask application by
$ export FLASK_APP=hello.py
$ flask run
The second command doesn't work for me.
$ flask run
Command 'flask' not found, but can be installed with:
sudo apt install python3-flask
Instead this works
python3 -m flask run
How can I make the second command works? If I run sudo apt install python3-flask, will I get two installations of flask?
Can the two commands be combined into one command without using environment variable?
Bear with me as I will try to explain the different pieces and how they all interconnect. export FLASK_APP=hello.py is setting an operating system environment variable called FLASK_APP and is simply pointing to the entry file to start your flask application. This is no different than setting any other environment variable on your operating system. Now the flask team has provided everyone with a command called flask run which can be used to start up your flask application and this command will use the value set within your FLASK_APP environment variable when it attempts to start your flask server. So the reason why your python3 -m flask run command works is because you're telling your operating system's install of python to run the flask run command as a script, which is how this command is intended to be invoked.
For reference:
-m mod : run library module as a script (terminates option list)
Additionally, python attempts to resolve modules from it's sys.path environment variable and it looks in the following order of directories to resolve the requested module:
The current directory where the script has been invoked. This is why you can always import modules contained in the same directory as one another.
The value of your PYTHONPATH environment variable
The standard library directory on your path
Lastly, the site packages directory, i.e. your third party packages like flask
Now the reason your flask run command didn't initially work is because python couldn't find flask within any of the four locations listed above. However, once you gave the -m python knew to look in your site-packages directory for flask and was able to find said module.
For reference you can see where python is looking to resolve modules by printing out the sys.path variable to the console:
import sys
print(sys.path)
Ok so that answers the first part of your first question, now as for the second part of your first question:
"If I run sudo apt install python3-flask, will I get two installations of flask?"
Yes, this would install flask globally on your system and I would highly advise against this as you can mess up your system pretty badly if you're not careful. So how do I avoid messing with my system level python configurations?
Virtualenv to the rescue, Virtual environments allow you to have a sandboxed area to play around with libraries. With the worst case scenario being you blow them away and start fresh if you screwed something up, without affecting your Operating System's install of python. You should have a one to one relationship between each python project and virtual environment. If you use virtualenv I highly suggest looking into Virtualenvwrapper which wraps virtualenv with easier to remember commands. Although I think all the cool kids are using pipenv now so you may want to look into that as well, I will leave that decision up to you. What's nice is once you've activated your virtual environment and are developing you can just use flask run since your virtual environment will be on your python path.
As for your second question: "Can the two commands be combined into one command without using environment variable?"
No you would still need to set the FLASK_APP environment variable to use flask run since it looks for the value of that environment variable to start your flask server. Perhaps you could try something like:
FLASK_APP=hello.py flask run
on the command line and see if that helps you, but you're still setting the FLASK_APP environment variable. Alternatively, you could just start the entry file for your flask server directly, with a:
python hello.py
I know that was a lot, but hopefully that helps clarify things for you!

Getting Error: 'No module named flask' in VSCode even when I have installed flask

I want to debug an application using Python and Flask in VSCode. I have installed Flask and the app runs perfectly fine through cmd. But, when I try to debug it through VSCode, it gives the following error:
cd 'c:\Users\Aditi\CleanHandymanApp';
${env:FLASK_APP}='NewApp'; ${env:PYTHONIOENCODING}='UTF-8';
${env:PYTHONUNBUFFERED}='1'; & 'C:\Users\Aditi\envs\CleanHandymanApp\Scripts\python.exe'
'c:\Users\Aditi\.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd_launcher.py' '--client' '--host'
'localhost' '--port' '63143' '-m' 'flask' 'run' '--no-debugger' '--no-reload'
No module named flask
Can you please help me.
This error message can occur if you installed the python3 version of flask but Visual Studio Code tries to run your project with python2.
Make sure to select the correct version of python in the editor. This can be done by running the command Python: Select Interpreter from the Command Palette (Ctrl+Shift+P).
Activate your virtualenv and run
pip3 install -r requirements.txt
to reinstall all packages inside the venv.
For some reason VS Code thought I was missing all my packages the first time I debugged even though the app was running fine locally.
Sometimes you can get this error if you loaded Flask into a folder which has sub-files. For instance, if you loaded flask into the parent folder with the virtual shell instance but you're running your code in the child file (let's say parent is called crypto_files and inside that is a python source code file called blockchain.py ), then in order to get flask to run properly you'd have to run the file like this:
python crypto_files/blockchain.py
This allows your machine to see Flask running inside crypto_files but also run blockchain.py .
OR, it's possibly you could just reload Flask into the sub(child)file... blockchain.py and then you'd run it from within the subfile.
This complication is mainly due to modern "virtual instances" and shells which are basically like creating a virtual computer-machine inside your ACTUAL hard machine. Flask does this to avoid running everywhere, and since Flask is modular it allows each of your projects to run different modular configurations of Flask to suit each project precisely. The alternative would be awful: you'd have to load the fattest version of Flask with dozens of add-ons for each project, and so all your git and all your projects would have tons of extra code. Flask is built to be very small at the core to avoid this problem (too verbose!).
If you have installed flask in virtual environment, you should have activated it first.
source /path to env dir/bin/activate #in linux
workon 'name of env' #windows
Another option is add sys.path.append('d:/programas/anaconda3/lib/site-packages') in c:\Users\Aditi.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd_launcher.py
Being that "d:/programas/anaconda3/lib/site-packages" should be modified by your local python packages.
Use this command in the terminal instead of selecting run code:
python3 "insert your file name here without the quotes"
e.g.: python3 example.py
I had a variant of the issue mentioned by #confusius. I had installed both Python 3.9 and Python 3.10. I had added Flask to Python 3.10. I had been using one vscode workspace which had selected Python 3.10. I started another project in a different vscode workspace and it had selected Python 3.9 by default, which I didn't notice because I thought it would select the same Python I had already selected in the other workspace.

nltk for python 3.6 in windows64

I'm new to python, I'm using Windows 10 and have python36 and I basically have to use nltk for my project and i basically have two questions.
1 I heard pip is automatically downloaded for versions 3+ but when I type pip install nltk in command prompt im getting the following error even though i added its path "C:\Users\dheeraj\AppData\Local\Programs\Python\Python36\Scripts\pip36" in advanced settings and ya in above path i tried pip36 and pip in both cases result is same.
'pip' is not recognized as an internal or external command,"
2 In www.nltk.org I found nltk for mac, unix and windows32 but not for windows64 ,does that mean it doesnt support for 64bit or is there any way for me to install nltk.
I had the same problem as you, but I accidentally found pip.exe in my python directory, so I navigated to said directory with CMD and ran the command pip install -U nltk and it worked.
Run the Python interpreter and type the commands:
import nltk>>>
nltk.download()>>>
A new window should open, showing the NLTK Downloader. Click on the File menu and select Change Download Directory. For central installation, set this to C:\nltk_data (Windows), /usr/local/share/nltk_data(Mac), or /usr/share/nltk_data (Unix). Next, select the packages or collections you want to download.
If you did not install the data to one of the above central locations, you will need to set the NLTK_DATA environment variable to specify the location of the data. (On a Windows machine, right click on “My Computer” then select Properties > Advanced > Environment Variables > User Variables > New...)
Test that the data has been installed as follows. (This assumes you downloaded the Brown Corpus):
from nltk.corpus import brown>>>
brown.words()>>>
['The', 'Fulton', 'County', 'Grand', 'Jury', 'said', ...]
Installing via a proxy web server
If your web connection uses a proxy server, you should specify the proxy address as follows. In the case of an authenticating proxy, specify a username and password. If the proxy is set to None then this function will attempt to detect the system proxy.
nltk.set_proxy('http://proxy.example.com:3128', ('USERNAME', 'PASSWORD'))>>>
>>> nltk.download()
Command line installation
The downloader will search for an existing nltk_data directory to install NLTK data. If one does not exist it will attempt to create one in a central location (when using an administrator account) or otherwise in the user’s filespace. If necessary, run the download command from an administrator account, or using sudo. The recommended system location is C:\nltk_data (Windows); /usr/local/share/nltk_data (Mac); and/usr/share/nltk_data `(Unix). You can use the -d flag to specify a different location (but if you do this, be sure to set the NLTK_DATA environment variable accordingly).
Run the command python -m nltk.downloader all. To ensure central installation, run the command sudo python -m nltk.downloader -d /usr/local/share/nltk_data all.
Windows: Use the “Run...” option on the Start menu. Windows Vista users need to first turn on this option, using Start -> Properties -> Customize to check the box to activate the “Run...” option.
Following are the steps I followed to resolve this issue:
Click on Python 3.6 Module Docs (32 bit). This will open in your default browser.
Click on pip(Package), displayed at the end of the page.
You will be redirected to a page displaying details of the package. Find the exact path from there. It will be something like c:\users\grove\appdata\local\programs\python\python36-32\lib\site-packages\pip
Run this on cmd prompt.
Once you're in pip folder type pip install -U nltk
Go back to Python Shell and type import nltk
Directly Search for pip folder and navigate throught that path example:
C:\Users\PAVAN\Environments\my_env\Lib\site-packages\pip>
Run cmd
and then run the command
pip install -U nltk
I will recommend you to use the Anaconda on Windows. Anaconda has nltk version for Python 64-bit. Now I'm using Python 3.6.4 64-bit and nltk.
Under python shell run:
import nltk
nltk.download()
then the downloader will be open in new window and you can download what you want.
First install the module
like pip install -U nltk
and the use the import statment in the command prompt or IDLE
import nltk

Resources