小编Tur*_*urn的帖子

Python。为从单独模块导入的类实例启用日志记录

再会。我正在尝试解决Python 中的登录问题。我正在使用Python 3.5.1。我有一个应用程序,它使用从其他模块导入的类。我无法为其启用日志记录。这是一个简单的表示:

# test.py
import logging

from test_class import TestClass


logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.FileHandler('test_log.log', mode='w'))


if __name__ == '__main__':
    logger.info('Importing class')
    t = TestClass()
    t.make_call()
    t.make_another_call()
    logger.info('End')

# test_class.py
import logging


class TestClass(object):

    def __init__(self):
        self.logger = logging.getLogger('test_class.TestClass')

    def make_call(self):
        self.logger.info('Make a call')

    def make_another_call(self):
        self.logger.info('Make another call')
Run Code Online (Sandbox Code Playgroud)

如您所见,记录器必须写入文件行(两行来自主模块,两行来自类。但是当我打开日志文件时,我看到:

# test_log.log
Importing class
End
Run Code Online (Sandbox Code Playgroud)

因此,来自类的两个记录器调用没有效果。知道吗,为什么它不起作用?先感谢您。

python logging python-3.x python-3.5

3
推荐指数
1
解决办法
8699
查看次数

从多个文件打印请求的行

我想从多个文件中获取特定的行.

我试过这样做:

sed -n "5p;10p" file1.txt file2.txt
Run Code Online (Sandbox Code Playgroud)

但它只打印第一个文件中的行,有没有人有解决方案?谢谢

awk sed

2
推荐指数
1
解决办法
329
查看次数

为什么这个变量引用非局部作用域不能解析?

这是一个寻找正整数aandb和 的最大公约数的例子a <= b。我从较小的a和一个一个的减号开始,检查它是否是两个数字的除数。

def gcdFinder(a, b):

    testerNum = a   

    def tester(a, b):
        if b % testerNum == 0 and a % testerNum == 0:
            return testerNum
        else:
            testerNum -= 1
            tester(a, b)

    return tester(a, b)

print(gcdFinder(9, 15))
Run Code Online (Sandbox Code Playgroud)

然后,我收到错误消息,

UnboundLocalError: local variable 'testerNum' referenced before assignment.

使用后global testerNum,它成功地3在Spyder控制台中显示了答案......

间谍的结果

但是在 pythontutor.com 中,它说NameError: name 'testerNum' is not defined链接)。

pythontutor的结果

Q1:在 Spyder 中,我认为这global testerNum是一个问题,因为 …

python scope global-scope python-3.x spyder

2
推荐指数
1
解决办法
530
查看次数

为什么我不能从字典中追加这个值?

我有一个程序,目的是模拟纸牌游戏21.以下是我的代码的重要元素,这是非常自我解释(我突出显示的行,我将在后面提到)

spades = ['2S','3S','4S','5S','6S','7S','8S','9S','10S','JS','QS','KS','AS']
hearts = ['2H','3H','4H','5H','6H','7H','8H','9H','10H','JH','QH','KH','AH']
clubs = ['2C','3C','4C','5C','6C','7C','8C','9C','10C','JC','QC','KC','AC']
diamonds = ['2D','3D','4D','5D','6D','7D','8D','9D','10D','JD','QD','KD','AD']
allCards = spades + hearts + clubs + diamonds

cardVal = {'2S':2,'3S':3,'4S':4,'5S': 5,'6S':6,'7S':7,'8S':8,'9S':9,'10S':10,'JS':10,'QS':10,'KS':10,'AS':11,
    '2H':2,'3H':3,'4H':4,'5H':5,'6H':6,'7H':7,'8H':8,'9H':9,'10H':10,'JH':10,'QH':10,'KH':10,'AH':11,
    '2C':2,'3C':3,'4C':4,'5C':5,'6C':6,'7C':7,'8C':8,'9C':9,'10C':10,'JC':10,'QC':10,'KC':10,'AC':11,
    '2D':2,'3D':3,'4D':4,'5D':5,'6D':6,'7D':7,'8D':8,'9D':9,'10D':10,'JD':10,'QD':10,'KD':10,'AD':11}

import random
random.shuffle(allCards)

playerCards = [allCards.pop() for i in range(2)]
dealerCards = [allCards.pop() for i in range(2)]
playerHand = []
dealerHand = []
playerHandVal = 0
dealerHandVal = 0

def handVal(playercards,playerhand,score):
    playerhand = []
    for i in playercards:
        playerhand.append(cardVal[i]) ####### LINE 29 ######
    score = sum(playerhand)
    print(score)

handVal(playerCards,playerHand,playerHandVal)
handVal(dealerCards,dealerHand,dealerHandVal)

def twist(playercards,playerhand,score): …
Run Code Online (Sandbox Code Playgroud)

python arrays dictionary python-3.x

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

为什么gcc不将逗号视为序列点?

我正在观察不同的行为,我认为它是C标准的一部分clanggcc(在我的mac或linux上的自制软件版本).问题是参数列表中的逗号是否是序列点.clang解释它,但gcc不是.

此代码演示了此问题:

#include <stdio.h>

int inner(int *v) {
  *v += 1;
  return 1;
}

int outer(int x, int y) {
  return y;
}

int main(int argc, char *argv[]) {
  int x = 4;
  printf ("result=%d\n", outer(inner(&x), x));
}
Run Code Online (Sandbox Code Playgroud)

结果如下:

$ clang -o comseq comseq.c && ./comseq
result=5
$ gcc-4.8 -o comseq comseq.c && ./comseq
result=4
$ gcc-5 -o comseq comseq.c && ./comseq
result=4
Run Code Online (Sandbox Code Playgroud)

我目前无法访问C标准的副本,但clang在我看到gcc解释之前,我非常确定这种行为是正确的.使用该--std=选项并没有改变我的结果.

ETA

在更好的阅读中,确实可以在 …

c gcc clang

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

我在Python 3中调用Dictionary中的函数

我有一个类,我有3个简单的函数,我将它们全部打包在字典中.目标是能够遍历调用函数的字典,但是,我收到了几个错误:

class Testa(object):
    def __init__(self, debt = None, equity = None):
        self.debt = debt
        self.equity = equity
    def tutu():
        print('hola')
    def foo(self):
        print('hello')
    def bar(self, debt=None, equity=None):
        return equity - debt

    variables = {'tutu':tutu,'foo':foo,'bar':bar}
Run Code Online (Sandbox Code Playgroud)

我得到的结果如下:

ra =Testa()
ra.variables['tutu']()
>>> hola
ra.variables['foo']()
>>> TypeError: foo() missing 1 required positional argument: 'self'
ra.variables['bar'](debt = 300, equity=400)
>>> TypeError: bar() missing 1 required positional argument: 'self'
Run Code Online (Sandbox Code Playgroud)

有什么线索可能是什么问题?谢谢.-

python dictionary function python-3.x

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

使用 sed 替换目录中所有文件中的字符串

我正在尝试查找并替换所有出现的这种情况:

 #include <boost
Run Code Online (Sandbox Code Playgroud)

有了这个:

#include </home/pi/Desktop/boost_1_66_0/boost
Run Code Online (Sandbox Code Playgroud)

使图书馆工作。这是我想出的:

sed -i 's/#include <boost/#include <\/home\/pi\/Desktop\/boost_1_66_0\/boost/g' *
Run Code Online (Sandbox Code Playgroud)

但给了我这个:

sed:无法编辑构建:不是常规文件

我是否转义了'/' 错误还是# 问题?

regex linux terminal sed

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

错误:'dict_values'对象不支持索引

我正在尝试使用Kaggle Bag of Words模块,并且在某一点上,它抛出了这个错误:

kmeans_clustering = KMeans( n_clusters = num_clusters )
idx = kmeans_clustering.fit_predict( word_vectors )
word_centroid_map = dict(zip( model.wv.index2word, idx ))
Run Code Online (Sandbox Code Playgroud)

现在,

for cluster in range(0,10):
        print("\nCluster %d" % cluster)
        words = []
        for i in range(0,len(word_centroid_map.values())):
            if( word_centroid_map.values()[i] == cluster ):
                words.append(word_centroid_map.keys()[i])
        print(words)
Run Code Online (Sandbox Code Playgroud)

错误是:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-f230ff75f988> in <module>()
      3         words = []
      4         for i in range(0,len(word_centroid_map.values())):
----> 5             if( word_centroid_map.values()[i] == cluster ):
      6                 words.append(word_centroid_map.keys()[i])
      7         print(words)

TypeError: 'dict_values' object does …
Run Code Online (Sandbox Code Playgroud)

python python-3.x

0
推荐指数
2
解决办法
7637
查看次数