Is there a NODE_ENV equivalent in Python?
I want to dynamically load JSON configurations to the python application based on the executing environment. In nodeJs, I do this by using the process.env.NODE_ENV.
For example,
I start the app like this,
NODE_ENV=production node server.js
And use the variable in the application like this,
if(process.env.NODE_ENV == "production") {
// Load the production config file here (eg: database.json)
} else {
// Load the development config file here (located in a different directory)
}
How can I achieve the same in Python? Or can I make use of python virtualenv or python setuptools to have a workaround?
For starters, you could do something like this.
import os
env = os.environ.get("PYTHON_ENV")
if(env =="production"):
//
else :
The script can be run with PYTHON_ENV="production" python myscript.py. Or you could use some library like dotenv(https://github.com/theskumar/python-dotenv).
you can try environs library in python
pip install environs
Related
I created a project that follows the example in MutPy's README file.
However, when I run mut.py --target calculator --unit-test test_calculator -m, it just opens mut.py instead of actually running MutPy.
The file has the following content:
#!c:\users\admin\appdata\local\programs\python\python39\python.exe
import sys
from mutpy import commandline
if __name__ == '__main__':
commandline.main(sys.argv)
The README doesn't mention any other configurations that need to be done and says that it should be compatible with Python 3.3+ (I'm on Python 3.9.6).
Is there something I'm doing wrong?
Are you runing this from cmd.exe?
If so try:
python.exe mut.py --target calculator --unit-test test_calculator -m
Note that you need python in your PATH Variable.
It will probably also work if you set python as the default application for .py files.
I have a Python script that can create an excel file with information from the input given by user from the HTML UI I created with a few html pages, css and javascript. I need this to work offline and I need to distribute it to clients.
How can I bundle this HTML UI and Python file so that the client doesn't require to install Python or any dependencies to work with my app? I think eel does the job by not requiring the client to install python to work with this but in eel the client should already have chrome installed right?
Edit:
my js:
function elect() {
console.log('Im in function right now');
let {PythonShell} = require('python-shell');
var path = require('path');
var options = {
scriptPath : path.join(__dirname, '/../engine/')
}
var axiexe = new PythonShell ('test sort.py', options);
axiexe.on('message', function (message) {
swal(message);
})
}
My dir is E:\Web\testing my app\GUI inside it I have the folder node_modules with #electron, .bin, python-shelletc folders.
I am working right now on the Electron app supplied with Python backend.
My flow is following:
1. install Pyshell as npm module.
2. create your Electron UI
3. Compile your python code using pyinstaller.
then comes the trick. Pyshell in fact uses also a python installed on the machine.
Alternative is to run a server in Python, I raised a question to myself. Why should I if I have very trivial functions?
Solution:
modify python-shell to make it run exe files, also I use a trick that I say path to python is my compile python_code.exe
and my script is null, then I commented lines in python-shell where check for script length occurred
In communicator.js for the build version use:
let options = {
mode: 'text',
pythonPath: "resources/app/python_build/electron_backend.exe"
};
pyshell = new PythonShell(' ', options);
while for development Pyshell will grab your Python installation from env. variables. So we need only to provide a .py file path
pyshell = new PythonShell('electron_backend.py');
In order to make it run please change source of the pyshell module, comment following:
// if (scriptPath.trim().length == 0)
// throw Error("scriptPath cannot be empty! You must give a script for python to run");
From my Windows 10 command line:
heroku config
yields the output:
=== test-bot Config Vars
GROUPME_BOT_ID: [111111111111111111]
My Python 3 code:
data = {
'bot_id' : os.getenv('GROUPME_BOT_ID'),
'text' : "hi",
}
print(data)
yields:
{'bot_id': None, 'text': 'hi'}
The bot_id is None instead of 111111111111111111. Why?
For testing, I execute my code from the command line of my Windows computer via:
python app.py
heroku:config only sets environment variables on Heroku. To run your code locally you will have to set your environment variables locally. (They can be different in development and production. That's the whole idea—they're environment-specific.)
There are several ways to do this. Here are two:
On your local machine you can use a .env file containing data in the format
VAR1=value
VAR2=value2
and then run your application using Foreman, which will automatically read the .env file and set appropriate environment variables:
foreman start
You can set environment variables using something like direnv, which will read an .envrc file for your project whenever you cd into its directory and set environment variables accordingly. In this case you don't need to use Foreman; python app.py should work fine.
There are editor and IDE plugins for direnv that can automate this in your editor as well.
I have a repo "A" with shared python build scripts which I today run in various "Execute shell" build steps in Jenkins. I seed this steps/scripts from job-dsl groovy code.
Using the newer Jenkins 2 Pipeline-concept in a repo "B" (where my app source code resides) what must my Jenkinsfile in this repo look like to keep it DRY and reuse my existing python build scripts?
I have studied the plugin 'workflow-cps-global-lib' and I have tried to setup "Pipeline Libraries" on my Jenkins master but since this setup groovy-oriented it does not just feel like the right way to go or I just does not get hang of the correct syntax. I cannot find any examples on this specific use case.
Basically I just want to to this in my Jenkinsfile:
Clone my source repo ('B') for my app
Make my shared python build scripts from my repo "A" available
Execute the python build scripts from various "execute shell" steps
Etcetera...
workflow-cps-global-lib is the way to go. Install it and setup in 'Manage Jenkins -> Configure System -> Global Pipeline Libraries to use your repository.
If you decided to use python scripts and not groovy, put all your python scripts in (root)/resources dir.
in your Jenkinsfile - load the script with libraryResource
script = libraryResource 'my_script.py'
and use it
sh script
(not enough reputation to add comment to accepted answer above)
Given a python script in /resources/myscript.py like this:
#!/usr/bin/env python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--echo")
args = parser.parse_args()
print(args.echo)
Use a Jenkins function like this:
def runPy(String scriptPath, def args) {
String script = libraryResource(scriptPath)
String argsString = args.join(' ')
sh "python3 -c '${script}' ${argsString}"
}
runPy('myscript.py', ['--echo', 'foo'])
For example, I have a Python script using the Google App Engine SDK:
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
The module db has a submodule Key, so I try to use autocomplete on it:
db.KTab
But at the bottom of the Vim window, I get the following:
-- Omni completion (^O^N^P) Pattern not found
How do I include the path to non-standard Python libraries so that Vim autocompletion can find them? And also display their docstrings?
You need to add your library files to your tags file. For instance, if you have installed the Google App Engine via pip in a virtual environment located in env/:
virtualenv --no-site-package env/
source env/bin/activate
pip install google_appengine
... then you should execute:
ctags -R --python-kinds=-i -o tags env/
If you did not install google_appengine through pip, then you should locate the path to your python libraries (hint: it should be indicated by $PYTHONPATH. And according to this reference page: "on Unix, this is usually .:/usr/local/lib/python.") and replace env/ by the path you found.
Finally, your .vimrc file should parse your tags file. For instance, in my .vimrc, I have:
set tags+=/path/to/my/tags
I grabbed this from natw's vimrc (I think...maybe sontek), but it should do the trick, so long as your packages are findable by your current install of Python. This lets you use gf, but also sets up searching these files for autocompletion. Note the py <<EOF part, which starts a section interpreted in Python. This means you'd have to have the python interpreter installed in vim to use it.
function! LoadPythonPath()
py <<EOF
# load PYTHONPATH into vim, this lets you hover over a module name
# and type 'gf' (for goto file) and open that file in vim. Useful
# and easier than rope for simple tasks
import os.path
import sys
import vim
for p in sys.path:
if os.path.isdir(p):
vim.command(r"set path+=%s" % (p.replace(" ", r"\ ")))
EOF
endfunction
Btw, I don't like to have this load automatically, so I set it to a function that intelligently loads/unloads when I call it/first enter a Python doc. And I add a let g:PythonPathLoaded=1 to the previous function.
function! GetPythonPath()
if !exists("g:PythonPathLoaded")
call LoadPythonPath()
return
elseif g:PythonPathLoaded
return
else
call LoadPythonPath()
endif
endfunction
And I have an unload function too...though I'm not sure whether this makes a huge difference.
function! UnloadPythonPath()
py <<EOF
# load PYTHONPATH into vim, this lets you hover over a module name
# and type 'gf' (for goto file) and open that file in vim. Useful
# and easier than rope for simple tasks
for p in sys.path:
if os.path.isdir(p):
vim.command(r"set path-=%s" % (p.replace(" ", r"\ ")))
EOF
let g:PythonPathLoaded = 0
endfunction
Hope this helps! Plus, an added bonus is that this will load your packages regardless of whether you are using virtualenv (since it, I believe, runs whatever is set as 'python' at the moment).