Executing command line script from Django & Python
I'm building a Django management command which is creating website screenshots using Paul Hammond's webkit2png script (http://www.paulhammond.org/webkit2png/) and stores them into my DB.
For this command I'm using the 'call' command from 'subprocess'. How do I execute this command in specific directory (temp/ under django project in this case)? My current code looks like this but it doesn't find the script to execute which is stored in my virtualenv site-pa开发者_运维百科ckages folder:
import os
from django.core.management.base import NoArgsCommand
from django.conf import settings
from subprocess import call
# Models
from reviews.models import Shop
class Command(NoArgsCommand):
def handle_noargs(self, **options):
# Shops
shops = Shop.objects.all()
path = os.path.join(settings.SITE_ROOT, '../env/lib/python2.6/site-packages')
for shop in shops:
print shop
command = "cd temp; python %s/webkit2png.py -F %s" % (path, shop.url)
call([command])
# Read the screenshot file and insert to model's ImageField
You need to use the cwd
parameter to call
. Also I'd recommend normalizing the path before using it.
path = os.path.normpath(os.path.join(settings.SITE_ROOT,
'../env/lib/python2.6/site-packages'))
for shop in shops:
print shop
call(["python", path + "/webkit2png.py", "-F", shop.url], cwd="temp")
# Read the screenshot file and insert to model's ImageField
call
takes the same arguments as Popen. You might find some more things there that help out as well. Also, it's best to split your command-line tokens up as separate strings in the list passed to call
and leave the shell
parameter at its default False
. This way, you don't have to worry about shell escaping, quoting, or whatever messing up your parameters.
This does not answer your question directly but : why do you need to use subprocess to call a python script ? You could just look at the "__main__
" code in the webkit2png.py file, import
it and use it.
精彩评论