running python script through shell_plus from command line
I have a python script that I run to populate my database.开发者_C百科 I usually run the script inside shell_plus because of the dependencies required. Is there a way to load the script into shell_plus and run everything from my linux command line without actually opening the shell_plus interface?
"Standalone Django scripts"
You bet!
I don't even recommend using shell_plus. I tend to store my utilities scripts in my app utility folder. Then I simply call them from a cron job or manually as needed. Here is framework script I base this off of. (Somewhat simplified)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import logging
import time
import time
import optparse
# DO NOT IMPORT DJANGO MODELS HERE - THIS NEED TO HAPPEN BELOW!!
# This needs to be able to be run when django isn't in the picture (cron) so we need
# to be able to add in the django paths when needed.
def getArgs():
"""
Simply get the options for running update people.
"""
p = optparse.OptionParser()
help = "The Python path to a settings module, e.g. "
help += "\"myproject.settings.main\". If this isn't provided, the "
help += "DJANGO_SETTINGS_MODULE environment variable will be used."
p.add_option("-s", "--settings", action = "store", type = "string",
dest = "settings", help = help)
help = "A directory to add to the Python path, e.g."
help += " \"/home/djangoprojects/myproject\"."
p.add_option("-y", "--pythonpath", action = "store", type = "string",
dest = "pythonpath", help = help)
p.add_option("-v", "--verbose", action = "count", dest = "verbose",
help = "Turn on verbose debugging")
p.set_defaults(settings = os.environ.get("DJANGO_SETTINGS_MODULE",
"settings"),
pythonpath = "", verbose = 0,
)
return p.parse_args()
def update(opt, loglevel=None):
"""
This is the main script used for updating people
"""
start = time.time()
# This ensures that our sys.path is ready.
for path in opt.pythonpath.split(":"):
if os.path.abspath(path) not in sys.path and os.path.isdir(path):
sys.path.append(os.path.abspath(path))
os.environ['DJANGO_SETTINGS_MODULE'] = opt.settings
from django.conf import settings
try:
if settings.SITE_ROOT not in sys.path: pass
except ImportError:
return("Your setting file cannot be imported - not in sys.path??")
# IMPORT YOUR CODE MODELS HERE
from apps.core.utility.ExampleExtractor import ExampleExtractor
# YOUR DJANGO STUFF GOES HERE..
example = ExampleExtractor(loglevel=loglevel, singleton=not(opt.multiple))
raw = example.get_raw()
results = example.update_django(raw)
log.info("Time to update %s entries : %s" % (len(results), time.time() - start))
return results
if __name__ == '__main__':
logging.basicConfig(format = "%(asctime)s %(levelname)-8s %(module)s \
%(funcName)s %(message)s", datefmt = "%H:%M:%S", stream = sys.stderr)
log = logging.getLogger("")
log.setLevel(logging.DEBUG)
opts, args = getArgs()
sys.exit(update(opts))
HTH!
精彩评论