grokpot
grokpot

Reputation: 1492

How do I execute a python script on Heroku?

I have a python script which I only need to run once (I don't want to have to commit it to the repo to send to the Cedar instance).

The Script aggregates data over my Django models and outputs a .csv file.

Normally in AWS, I would scp the script to the server, manage.py shell < script.py, and scp the produced .csv back to my machine.

I understand Heroku file systems are ephemeral, but is there a way to retrieve produced files on Heroku servers without uploading them to S3?

Here's my best shot:

cat script.py | heroku run manage.py shell --app appname

Works for a one line script, but not with line breaks.

Also, the above script will only produce command line output, not return a .csv file.

Upvotes: 5

Views: 6639

Answers (3)

user916367
user916367

Reputation:

You are nearly there. The issue you are having is more related to how the typical shell syntax works.

You have cat script.py | heroku run manage.py shell --app appname which pipes in the script with no line breaks.

To get your line breaks try this.

heroku run python -c "`cat script.py`" --app appname

The key is wrapping the backticks in double quotes, that way line breaks in the script are preserved.

Upvotes: 1

LaLa
LaLa

Reputation: 652

I wanted to execute a python script manually in heroku one single time. That's how it worked:

  1. import django in your script
  2. add the line django.setup() in your python script (that is important to be able to use the created models in django)
  3. shell command (has to be executed in your git repository): heroku run bash
  4. bash command: export DJANGO_SETTINGS_MODULE=projectsname.settings
  5. bash command: cd projectsname
  6. bash commmand: python yourscriptname.py

Upvotes: 3

jraede
jraede

Reputation: 6896

Heroku doesn't give you write permissions anywhere on your dyno (the only files it writes are the ones it checks out from your master branch when you push an update, and any dependencies). You'll have to upload your output to S3, save it to the log, or find some other delivery mechanism (email?)

Upvotes: 3

Related Questions