小编Ivi*_*vic的帖子

如何实现命令行切换到我的脚本?

我是python的新手。我正在编写一个计算单词、行和字符的程序。当我尝试使用命令行开关时,我开始遇到问题:-w、-l、-c,直到那时一切正常。

我阅读了有关 argparse 的 stackoverflow 和 python 文档的帖子,但我现在不知道如何实现 argparse 库以及与它一起使用的代码。

当我跑 python wc.py file.txt --l

我得到

太多值无法解压缩

有人可以帮我解决这个问题吗?

from sys import argv
import os.path
import argparse

script, filename = argv


def word_count(filename):
    my_file = open(filename)
    counter = 0
    for x in my_file.read().split():
        counter += 1
    return counter
    my_file.close()

def line_count(filename):
    my_file = open(filename, 'r').read()
    return len(my_file.splitlines())
    my_file.close()

def character_count(filename):
    my_file = open(filename, 'r').read()
    return len(my_file)
    my_file.close()

parser = argparse.ArgumentParser()
parser.add_argument('--w', nargs='+', help='word help')
parser.add_argument('--l', nargs='+', help='line help')
parser.add_argument('--c', nargs='+', help='character …
Run Code Online (Sandbox Code Playgroud)

python python-2.7 argparse

0
推荐指数
1
解决办法
2632
查看次数

如何调用模型方法?

我试图只显示不超过4天的对象.我知道我可以使用过滤器:

new = Books.objects.filter(pub_date__gt = datetime.now() - timedelta(days=4))
Run Code Online (Sandbox Code Playgroud)

但我真的想用一种模态方法进行锻炼.

该方法在模型Book中定义,称为published_recetnly.

所以我的问题是如何在views.py中调用模态方法?

这是我目前的代码:

views.py

def index(request):
    new = Books.objects.filter(pub_date__gt = datetime.now() - timedelta(days=4))
    return render_to_response('books/index.html', {'new':new}, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

的index.html

 {% if book in new %}
    {{ book.title }}
 {% endif %}
Run Code Online (Sandbox Code Playgroud)

models.py

class Book(models.Model)
    pub_date = models.DateTimeField('date published')

    def published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=4) <= self.pub_date <= now
Run Code Online (Sandbox Code Playgroud)

python django django-models django-queryset django-managers

0
推荐指数
1
解决办法
619
查看次数