小编vic*_*ooi的帖子

Python strptime()和时区?

我有一个使用IPDDump创建的Blackberry IPD备份的CSV转储文件.这里的日期/时间字符串看起来像这样(EST澳大利亚时区在哪里):

Tue Jun 22 07:46:22 EST 2010
Run Code Online (Sandbox Code Playgroud)

我需要能够在Python中解析这个日期.起初,我尝试使用strptime()datettime中的函数.

>>> datetime.datetime.strptime('Tue Jun 22 12:10:20 2010 EST', '%a %b %d %H:%M:%S %Y %Z')
Run Code Online (Sandbox Code Playgroud)

但是,由于某种原因,返回的datetime对象似乎没有任何tzinfo关联它.

我在这个页面上读到的显然是datetime.strptime默默地丢弃了tzinfo,但是,我检查了文档,我找不到任何有关此处记录的效果.

我已经能够使用第三方Python库dateutil来解析日期,但是我仍然很好奇我是如何使用内置strptime()错误的?有什么方法可以strptime()很好地与时区玩吗?

python timezone datetime

141
推荐指数
4
解决办法
14万
查看次数

在Node.js中解析巨大的日志文件 - 逐行读取

我需要在Javascript/Node.js中解析大型(5-10 Gb)日志文件(我正在使用Cube).

日志看起来像:

10:00:43.343423 I'm a friendly log message. There are 5 cats, and 7 dogs. We are in state "SUCCESS".
Run Code Online (Sandbox Code Playgroud)

我们需要读取每一行,进行一些解析(例如剥离5,7然后SUCCESS),然后使用他们的JS客户端将这些数据泵入Cube(https://github.com/square/cube).

首先,Node中逐行读取文件的规范方式是什么?

这似乎是在线相当常见的问题:

许多答案似乎指向一堆第三方模块:

但是,这似乎是一项相当基本的任务 - 当然,在stdlib中有一种简单的方法可以逐行读取文本文件吗?

其次,我需要处理每一行(例如,将时间戳转换为Date对象,并提取有用的字段).

什么是最好的方法,最大化吞吐量?是否有某种方法不会阻止每行读取或将其发送到Cube?

第三 - 我猜测使用字符串拆分,并且JS等价的contains(IndexOf!= -1?)将比正则表达式快得多?有没有人在Node.js中解析大量文本数据方面有很多经验?

干杯,维克多

parsing logfile-analysis node.js

104
推荐指数
7
解决办法
8万
查看次数

Matplotlib - 向下移动X轴标签,但不向下移动X轴

我正在使用Matplotlib绘制直方图.使用上一个问题的提示:Matplotlib - 标记每个bin,我或多或少地解决了问题.

最后一个问题 - 先前 - x轴标签("时间(以毫秒为单位)")在x轴刻度线下面呈现(0.00,0.04,0.08,0.12等)

无填充 - 图下方的轴标签

使用Joe Kingston的建议(见上面的问题),我尝试使用:

ax.tick_params(axis='x', pad=30)
Run Code Online (Sandbox Code Playgroud)

但是,这会同时移动x轴刻度线(0.00,0.04,0.08,0.12等)以及x轴标签("时间(以毫秒为单位)"):

30填充 - 轴标签和刻度标记都已移动

有没有办法只将x轴标签移动到三行数字下面?

Nb:您可能需要直接打开下面的PNG - 右键单击​​图像,然后单击查看图像(在FF中),或在新选项卡中打开图像(Chrome).由SO完成的图像调整大小使它们几乎不可读

python graphing matplotlib

95
推荐指数
2
解决办法
11万
查看次数

使用Python Logging记录消息两次

我正在使用Python日志记录,出于某种原因,我的所有消息都出现了两次.

我有一个配置日志记录的模块:

# BUG: It's outputting logging messages twice - not sure why - it's not the propagate setting.
def configure_logging(self, logging_file):
    self.logger = logging.getLogger("my_logger")
    self.logger.setLevel(logging.DEBUG)
    self.logger.propagate = 0
    # Format for our loglines
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    # Setup console logging
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(formatter)
    self.logger.addHandler(ch)
    # Setup file logging as well
    fh = logging.FileHandler(LOG_FILENAME)
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(formatter)
    self.logger.addHandler(fh)
Run Code Online (Sandbox Code Playgroud)

稍后,我调用此方法来配置日志记录:

if __name__ == '__main__':
    tom = Boy()
    tom.configure_logging(LOG_FILENAME)
    tom.buy_ham()
Run Code Online (Sandbox Code Playgroud)

然后说,buy_ham模块,我打电话给:

self.logger.info('Successfully able to write …
Run Code Online (Sandbox Code Playgroud)

python logging

78
推荐指数
6
解决办法
4万
查看次数

Django Forms和Bootstrap - CSS类和<divs>

我正在使用Twitter Bootstrap和Django来渲染表单.

Bootstrap可以很好地格式化你的表单 - 只要你有CSS它期望包含的类.

但是,我的问题是Django生成的表单{{ form.as_p }}不能很好地与Bootstrap一起呈现,因为它们没有这些类.

例如,Django的输出:

    <form class="horizontal-form" action="/contact/" method="post">
        <div style='display:none'>
            <input type='hidden' name='csrfmiddlewaretoken' 
                   value='26c39ab41e38cf6061367750ea8c2ea8'/>
        </div>
        <p><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" value="FOOBAR" maxlength="20" /></p>
        <p><label for="id_directory">Directory:</label> <input id="id_directory" type="text" name="directory" value="FOOBAR" maxlength="60" /></p>
       <p><label for="id_comment">Comment:</label> <textarea id="id_comment" rows="10" cols="40" name="comment">Lorem ipsum dolor sic amet.</textarea></p>
       <p>
           <label for="id_server">Server:</label>
           <select name="server" id="id_server">
               <option value="">---------</option>
               <option value="1" 
                   selected="selected">sydeqexcd01.au.db.com</option>
               <option value="2">server1</option>
               <option value="3">server2</option>
               <option value="4">server3</option>
           </select>
       </p>
       <input type="submit" value="Submit" />
    </form> …
Run Code Online (Sandbox Code Playgroud)

css django twitter-bootstrap

66
推荐指数
5
解决办法
8万
查看次数

Matplotlib - 标记每个bin

我目前正在使用Matplotlib来创建直方图:

在此输入图像描述

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as pyplot
...
fig = pyplot.figure()
ax = fig.add_subplot(1,1,1,)
n, bins, patches = ax.hist(measurements, bins=50, range=(graph_minimum, graph_maximum), histtype='bar')

#ax.set_xticklabels([n], rotation='vertical')

for patch in patches:
    patch.set_facecolor('r')

pyplot.title('Spam and Ham')
pyplot.xlabel('Time (in seconds)')
pyplot.ylabel('Bits of Ham')
pyplot.savefig(output_filename)
Run Code Online (Sandbox Code Playgroud)

我想让x轴标签更有意义.

首先,这里的x轴刻度似乎限于五个刻度.无论我做什么,我似乎无法改变这一点 - 即使我添加更多xticklabels,它只使用前五个.我不确定Matplotlib如何计算这个,但我认为它是从范围/数据中自动计算的?

有没有什么办法可以提高x-tick标签的分辨率 - 甚至可以提高每个条形码/ bin 的分辨率

(理想情况下,我也希望以微秒/毫秒重新格式化秒数,但这是另一天的问题).

其次,我想要标记每个单独的条形图 - 包含该条形图中的实际数字,以及所有条形图总数的百分比.

最终输出可能如下所示:

在此输入图像描述

Matplotlib有可能吗?

干杯,维克多

python graphing visualization matplotlib histogram

64
推荐指数
1
解决办法
8万
查看次数

Python - 避免在函数之间传递记录器引用?

我有一个使用内置的简单Python脚本logging.

我正在配置函数内的日志记录.基本结构将是这样的:

#!/usr/bin/env python
import logging
import ...

def configure_logging():
    logger = logging.getLogger("my logger")
    logger.setLevel(logging.DEBUG)
    # Format for our loglines
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    # Setup console logging
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(formatter)
    logger.addHandler(ch)
    # Setup file logging as well
    fh = logging.FileHandler(LOG_FILENAME)
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    return logger

def count_parrots():
    ...
    logger.debug??

if __name__ == '__main__':
    logger = configure_logging()
    logger.debug("I'm a log file")
    parrots = count_parrots()
Run Code Online (Sandbox Code Playgroud)

我可以从内部调用logger __main__.但是,如何从count_parrots()函数内部调用logger?处理像这样的记录器的最pythonic方法是什么?

python logging

49
推荐指数
3
解决办法
4万
查看次数

cx_Oracle和异常处理 - 良好实践?

我正在尝试使用cx_Oracle连接到Oracle实例并执行一些DDL语句:

db = None
try:
    db = cx_Oracle.connect('username', 'password', 'hostname:port/SERVICENAME')
#print(db.version)
except cx_Oracle.DatabaseError as e:
    error, = e.args
    if error.code == 1017:
        print('Please check your credentials.')
        # sys.exit()?
    else:
        print('Database connection error: %s'.format(e))
cursor = db.cursor()
try:
    cursor.execute(ddl_statements)
except cx_Oracle.DatabaseError as e:
    error, = e.args
    if error.code == 955:
        print('Table already exists')
    if error.code == 1031:
        print("Insufficient privileges - are you sure you're using the owner account?")
    print(error.code)
    print(error.message)
    print(error.context)
cursor.close()
db.commit()
db.close()
Run Code Online (Sandbox Code Playgroud)

但是,我不太确定这里的异常处理的最佳设计是什么.

首先,我db在try块中创建对象,以捕获任何连接错误.

但是,如果它无法连接,那么db将不再存在 …

python oracle cx-oracle

25
推荐指数
1
解决办法
5万
查看次数

Django模型 - 选择与外键?

据我所知,在Django中,ORM不支持MySQL或PostgreSQL中的ENUM类型,因为它最初是MySQL扩展,并且不能在其他数据库类型中移植.因此,两个选项是对模型使用"choices"参数,或使用外键引用.

这些方法的优点和缺点是什么?

对于像性别这样的东西,我假设你会使用"选择",例如:

GENDER_CHOICES = (
    ('M', 'Male'),
    ('F', 'Female'),
)
...
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
Run Code Online (Sandbox Code Playgroud)

但是,对于像州名这样的东西,使用单独的表和该表的外键的原因是什么?

state = models.ForeignKey(AustralianState)
Run Code Online (Sandbox Code Playgroud)

在什么情况下你会使用一个与另一个?

干杯,维克多

django django-models

21
推荐指数
2
解决办法
3656
查看次数

Mercurial - 无法锁定工作目录

我们有一个Web应用程序,我们正在部署到远程Ubuntu服务器.

该应用程序存储在BitBucket上,我们还使用了Fabric脚本来自动部署应用程序.

在服务器上,我们在/ var/www/name_of_site中有应用程序的文件,此文件夹是Mercurial存储库.这些文件由用户www-data,组www-data拥有,并且是可写组的.

当我尝试登录服务器并在存储库中执行"hg add"时,我得到一个:

adding fabfiles/fabfile.py
abort: could not lock working directory of /var/www/site_name: Permission denied
Run Code Online (Sandbox Code Playgroud)

我尝试将自己添加到www-data,它仍然提供该错误消息.我能够在/ var/www/site_name中创建文件夹/文件.

我在这里做错了吗?权限应该不同吗?

干杯,维克多

deployment mercurial

16
推荐指数
1
解决办法
9912
查看次数