从 Django & 执行命令行脚本Python [英] Executing command line script from Django & Python
问题描述
我正在构建一个 Django 管理命令,它使用 Paul Hammond 的 webkit2png 脚本 (http://www.paulhammond.org/webkit2png/) 并将它们存储到我的数据库中.
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.
对于这个命令,我使用了来自subprocess"的call"命令.如何在特定目录(本例中为 django 项目下的 temp/)中执行此命令?我当前的代码看起来像这样,但它没有找到要执行的脚本,该脚本存储在我的 virtualenv 站点包文件夹中:
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-packages 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
推荐答案
您需要使用 cwd
参数来call
.此外,我建议在使用之前将路径标准化.
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
采用与 打开.您可能会在那里找到更多有用的东西.此外,最好将您的命令行标记拆分为传递给 call
的列表中的单独字符串,并将 shell
参数保留为其默认的 False
>.这样,您就不必担心 shell 转义、引用或任何弄乱参数的问题.
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.
这篇关于从 Django & 执行命令行脚本Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!