I have a simple script that executes a flask command called sendemail (located in the "main" blueprint).
The "task" script, located in /home/ubuntu/tasks:
cd /home/ubuntu/app
source venv/bin/activate
flask main sendemail
deactivate
When I run (from anywhere, including the home directory)
bash /home/ubuntu/tasks/task
The function runs exactly as intended. However, when I add this same script to crontab, it produces an error, emailing me this message:
/home/ubuntu/tasks/task: line 4: flask: command not found
I've made sure that I have the latest flask installed and assume this might have something to do with the PATH variables - how can I fix/debug this?
The activation doesn’t work in the cron because you don’t have the same environment variables. You can use set > /path/to/your.log to diagnose…
You can simplify your scrip by calling Flask directly:
/home/ubuntu/app/venv/bin/flask main sendemail
Related
I have a weird problem with some code I want to run. The code itself should not be the problem since it is downloaded from a Udemy class and not modified:
# coding=utf-8
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route("/")
def hello():
items = ["Apfel", "Birne", "Banane"]
return render_template("start.html", name="Max Mustermann", items=items)
#app.route("/test")
def test():
name = request.args.get("name")
return render_template("test.html", name=name)
I found online that, to start the emulated webserver(?) I have to rund the following temrinal commands before I can see the output:
(base) Christophs-MBP:13-23 chris$ export FLASK_APP=run.py run flask
(base) Christophs-MBP:13-23 chris$ export FLASK_APP=run.py run flask
(base) Christophs-MBP:13-23 chris$ export FLASK_APP=run.py
(base) Christophs-MBP:13-23 chris$ run flask
bash: run: command not found
No reaction to my terminal commands
Basically there is no reaction to the command to start the server(?).It should reply with "Running on 127.0.0.1:5000" as soon as I've run the command once.
If I go to my browser, there is no page when I address http://127.0.0.1:5000. What am I doing wrong? I am pretty new to Python and an absolute rookie regarding the terminal. Not sure if I broke something there, since trying to install pyenv to manage my Python installs better as recommended by a friend does not work either (I cannot update the SDK headers as described on RealPython
What are the export statements?
On Mac, export key=value creates a new (or updates an existing one) environment variable - the tutorial most likely simply asked you to provide one where key is FLASK_APP and value is a path to your app.
To verify it's been saved correctly, you can list the variables by just typing export in the terminal and finding out what's inside each of the environment variables on your system (if you want to only view FLASK_APP you can type export | grep FLASK_APP).
Why do you need FLASK_APP?
When you call flask run in your terminal, you will see the following message:
Error: Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py"
module was not found in the current directory.
I presume your file is called run.py, therefore none of the conditions are met. You could rename run.py to app.py and simply type flask run in the terminal, but you can also type export FLASK_APP=<path-to-run.py>. It seems the tutorial author decided to do the latter. Keep in mind that if you rename your file to app.py you will need to run flask run within the directory that file lives in. You can change directory in the terminal using cd command.
Why do you get bash: run: command not found?
bash is a language running inside your terminal, and it only knows of a few commands - it is not aware of any run commands. It does however know about flask command once you have installed it on your machine. Within the command's output there is a part which includes a run command:
Commands:
routes Show the routes for the app.
run Run a development server.
shell Run a shell in the app context.
Therefore, what you want to do is type flask run instead of just run in your terminal.
I've been trying to debug this for a while now and I feel like I've tried everything.
Code is slightly modified with *** for company reasons.
The following executes as expected when run from a session as my local user.
/var/www/****/***/run.sh path_to_my/script.py 2>&1 >> /var/www/****/***/test.log
Where run.sh is just a wrapper for running Python in a virtualenv:
#!/usr/bin/env bash
wd=$(dirname $0)
source ${wd}/virtualenv/bin/activate
python ${wd}/$1
I have placed a print statement inside of the Python main to show that it's being executed.
if __name__ == "__main__":
print("I got in here...")
When running the command as my local user, the log will contain this printed statement. However, when run in cron as:
*/30 * * * * /var/www/****/***/run.sh path_to_my/script.py 2>&1 >> /var/www/****/***/test.log
I do not get any printed statement, nor do I receive any error output from the 2>&1.
My permissions are 755 on both the .sh and .py scripts.
Everything works as expected except when run via cron.
Am I missing something? Does cron not use .bashrc for the crontab user?
First make sure your local cronjob is running by putting the following in the crontab file and check to see if it get written out at /tmp/env.output after a minute or two
* * * * * env > /tmp/env.output
Second make sure the user running the crontab has permission to write to the /var/www/****/***/test.log file
Third try changing your script to
wd=$(dirname $0)
cd $wd
source activate
python ${wd}/$1
Edited: Anders was able to figure out the answer by himself by adding PYTHONPATH to the cron environment: export PYTHONPATH="${PYTHONPATH}:${wd}"
I am trying to use Kubernetes python SDK.
I tried to run the following code:
from kubernetes import client, config
# Configs can be set in Configuration class directly or using helper utility
config.load_kube_config()
v1 = client.CoreV1Api()
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
It failed with lots of errors.
When I run the same code with python from a shell, the same issue.
When I run the same code with sudo python from shell, it works.
I am trying to run PyCharm interperte as root.
Following the instruction from JetBrains, I created a script shell with the name pythonCustomInt.sh that contains:
sudo python
I went to PyCharm settings > Project Interpreter and changed the Base interpreter to /<path>/pythonCutomInt.sh but it writes an error:
Environment location directory is not empty
I am not sure where I need to put the script.
Any idea?
I ran sudo -s and then from the pycharm folder (pycharm-community-2018.1.4/bin) I ran sh ./pycharm.sh and it worked.
I am using Laradock and want to be able to run a python script from my laravel app using Symfony Process. From inside the root on my container I can run "python3 script_name.py arg1" and it runs just fine. pip list shows all modules needed. When I run it from inside Laravel, it tells me:
"import pymysql ImportError: No module named 'pymysql'"
I have used a non-docker Laravel app to do this just fine, using:
$script = storage_path().'/app/script.py';
$process = new Process('python3 '. $script." ".session('division'));
What am I missing?
On *nix make sure that PYTHONPATH is configured correctly for all users or try to set full path to python3.
How to check
At first your php user
php -r "print shell_exec( 'whoami' );" // somebody
When run
su somebody python3 script_name.py arg1
I am working with a django app called django-mailbox. The purpose of this is to import email messages via pop3 and other protocols and store them in a db. I want to do this at regular intervals via a chron. In the documentation http://django-mailbox.readthedocs.org/en/latest/topics/polling.html it states:
Using a cron job
You can easily consume incoming mail by running the management command named getmail (optionally with an argument of the name of the mailbox you’d like to get the mail for).:
python manage.py getmail
Now I can run this at the command line locally and it works but if this was deployed to an outside server which was only accessible by a URL how would this command be given?
If you are using a virtual env use the python binary from the virtualenv
* * * * * /path/to/virtualenv/bin/python /path/to/project/manage.py management_command
on the server machine:
$ sudo crontab -l
no crontab for root
$ sudo crontab -e
no crontab for root - using an empty one
Select an editor. To change later, run 'select-editor'.
1. /bin/ed
2. /bin/nano <---- easiest
3. /usr/bin/vim.basic
4. /usr/bin/vim.tiny
Choose 1-4 [2]:
choose your preferred editor
then see http://en.wikipedia.org/wiki/Cron for how to schedule when will the command run, direct it to some .sh file on your machine, make sure you give full path as this is going to run in root user context.
the script the cron will run may look something like:
#!/bin/bash
cd /absolute/path/to/django/project
/usr/bin/python ./manage.py getmail