Questions tagged «python»

Python是一种多范式,动态类型的多用途编程语言。它旨在快速学习,理解和使用并强制使用干净统一的语法。请注意,Python 2自2020年1月1日起已不再受支持。不过,对于特定于版本的Python问题,请添加[python-2.7]或[python-3.x]标签。使用Python变体或库(例如Jython,PyPy,Pandas,Numpy)时,请将其包含在标签中。

11
在鼻子下面测试Python代码时应如何验证日志消息?
我正在尝试编写一个简单的单元测试,该测试将验证在特定条件下我的应用程序中的类将通过标准日志记录API记录错误。我想不出最干净的方法来测试这种情况。 我知道鼻子已经通过它的日志记录插件捕获了日志输出,但这似乎旨在作为失败测试的报告和调试辅助工具。 我可以看到两种方法: 以零散方式(mymodule.logging =模拟日志模块)或使用适当的模拟库来模拟日志记录模块。 编写或使用现有的鼻子插件捕获输出并进行验证。 如果我采用前一种方法,那么我想知道在嘲笑日志记录模块之前将全局状态重置为原来状态的最干净方法是什么。 期待您对此的提示和技巧...

2
没有返回任何内容时处理JSON解码错误
我正在解析json数据。我的解析没有问题,我正在使用simplejson模块。但是某些api请求返回空值。这是我的示例: { "all" : { "count" : 0, "questions" : [ ] } } 这是我解析json对象的代码段: qByUser = byUsrUrlObj.read() qUserData = json.loads(qByUser).decode('utf-8') questionSubjs = qUserData["all"]["questions"] 正如我提到的一些请求,我得到以下错误: Traceback (most recent call last): File "YahooQueryData.py", line 164, in <module> qUserData = json.loads(qByUser) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/simplejson/__init__.py", line 385, in loads return _default_decoder.decode(s) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/simplejson/decoder.py", line …

7
抽象属性(不是属性)?
定义抽象实例属性而不是属性的最佳实践是什么? 我想写一些像: class AbstractFoo(metaclass=ABCMeta): @property @abstractmethod def bar(self): pass class Foo(AbstractFoo): def __init__(self): self.bar = 3 代替: class Foo(AbstractFoo): def __init__(self): self._bar = 3 @property def bar(self): return self._bar @bar.setter def setbar(self, bar): self._bar = bar @bar.deleter def delbar(self): del self._bar 属性很方便,但是对于不需要计算的简单属性来说,它们是过大的。这对于将由用户进行子类化和实现的抽象类尤为重要(我不想强迫某人@property只可以在中编写代码self.foo = foo就使用__init__)。 Python问题中的抽象属性仅建议使用@property和的答案@abstractmethod:它不能回答我的问题。 通过抽象类属性的ActiveState配方AbstractAttribute可能是正确的方法,但是我不确定。它也仅适用于类属性,而不适用于实例属性。
78 python  abstract 

9
standard_init_linux.go:178:exec用户进程导致“ exec格式错误”
码头工人开始抛出此错误: standard_init_linux.go:178:exec用户进程导致“ exec格式错误” 每当我运行带有CMD或ENTRYPOINT的特定docker容器时,不考虑文件的任何更改,然后删除CMD或ENTRYPOINT。这是我一直在使用的docker文件,该文件在大约一个小时前运行良好: FROM buildpack-deps:jessie ENV PATH /usr/local/bin:$PATH ENV LANG C.UTF-8 RUN apt-get update && apt-get install -y --no-install-recommends \ tcl \ tk \ && rm -rf /var/lib/apt/lists/* ENV GPG_KEY 0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D ENV PYTHON_VERSION 3.6.0 ENV PYTHON_PIP_VERSION 9.0.1 RUN set -ex \ && buildDeps=' \ tcl-dev \ tk-dev \ ' …
78 python  linux  bash  docker 

13
无法通过pip install安装psycopg2软件包…这是因为Sierra吗?
我正在为一个讲座做一个项目,我需要下载软件包psycopg2才能与正在使用的postgresql数据库一起使用。不幸的是,当我尝试点子安装psycopg2时,会弹出以下错误: ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command '/usr/bin/clang' failed with exit status 1 ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: …
78 python  pip  psycopg2 

6
在python项目中使用相对路径读取文件
说我有一个Python项目,其结构如下: project /data test.csv /package __init__.py module.py main.py __init__.py: from .module import test module.py: import csv with open("..data/test.csv") as f: test = [line for line in csv.reader(f)] main.py: import package print(package.test) 当我运行时main.py,出现以下错误: C:\Users\Patrick\Desktop\project>python main.py Traceback (most recent call last): File "main.py", line 1, in <module> import package File "C:\Users\Patrick\Desktop\project\package\__init__.py", line …

4
用威尔士语计数文本中的字母
如何计算Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch中的字母? print(len('Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')) 说58 好吧,如果那是那么容易,我不会问你,现在可以吗? 维基百科说(https://en.wikipedia.org/wiki/Llanfairpwllgwyngyll#Placename_and_toponymy) 名称的长格式是英国最长的地名,也是世界上最长的地名之一,共58个字符(因为“ ch”和“ ll”是二字,所以为51个“字母”,在英文字母中被视为单个字母)。威尔士语)。 所以我想算一下,得到答案51。 对。 print(len(['Ll','a','n','f','a','i','r','p','w','ll','g','w','y','n','g','y','ll','g','o','g','e','r','y','ch','w','y','r','n','d','r','o','b','w','ll','ll','a','n','t','y','s','i','l','i','o','g','o','g','o','g','o','ch'])) 51 是的,但这很欺骗,显然我想使用单词作为输入,而不是列表。 维基百科还说威尔士语中的有向字母是ch,dd,ff,ng,ll,ph,rh,th https://zh.wikipedia.org/wiki/威尔士orthography#Digraphs 所以我们走了。让我们加长长度,然后取消重复计算。 word='Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch' count=len(word) print('starting with count of',count) for index in range(len(word)-1): substring=word[index]+word[index+1] if substring.lower() in ['ch','dd','ff','ng','ll','ph','rh','th']: print('taking off double counting of',substring) count=count-1 print(count) 这使我走得很远 starting with count of 58 taking off double counting of Ll …

10
如何在keras中获得可复制的结果
每次我imdb_lstm.py从Keras框架(https://github.com/fchollet/keras/blob/master/examples/imdb_lstm.py)运行示例时,我都会得到不同的结果(测试准确性)。代码包含np.random.seed(1337)在顶部,而不是任何keras进口。应该防止它为每次运行生成不同的数字。我想念什么? 更新:如何复制: 安装Keras(http://keras.io/) 多次执行https://github.com/fchollet/keras/blob/master/examples/imdb_lstm.py。它将训练模型并输出测试精度。 预期结果:每次运行的测试准确性均相同。 实际结果:每次运行的测试准确性都不同。 UPDATE2:我正在Windows 8.1和MinGW / msys上运行它,模块版本: theano 0.7.0 numpy 1.8.1 scipy 0.14.0c1 UPDATE3:我将问题缩小了一点。如果我在GPU上运行示例(设置theano标志device = gpu0),则每次都会获得不同的测试准确性,但是如果我在CPU上运行,那么一切都会按预期进行。我的显卡:NVIDIA GeForce GT 635)
78 python  numpy  theano  keras 

5
Python:使用索引作为值将列表转换为字典
我正在尝试转换以下列表: list = ['A','B','C'] 像这样的字典: dict = {'A':0, 'B':1, 'C':2} 我尝试了其他职位的答案,但没有任何帮助。我现在有以下代码: {list[i]: i for i in range(len(list))} 这给了我这个错误: unhashable type: 'list' 任何帮助深表感谢。谢谢。



6
为什么我的南方移民不工作?
首先,创建数据库。 create database mydb; 我在安装的应用程序中添加“南”。然后,我转到本教程:http : //south.aeracode.org/docs/tutorial/part1.html 本教程告诉我要这样做: $ py manage.py schemamigration wall --initial >>> Created 0001_initial.py. You can now apply this migration with: ./manage.py migrate wall 太好了,现在我迁移了。 $ py manage.py migrate wall 但这给了我这个错误... django.db.utils.DatabaseError: (1146, "Table 'fable.south_migrationhistory' doesn't exist") 因此,我使用Google(它永远都行不通。因此我在Stackoverflow上问了870个问题),并得到以下页面:http : //groups.google.com/group/south-users/browse_thread/thread/d4c83f821dd2ca1c 好吧,所以我按照指示 >> Drop database mydb; >> Create …

11
在Mac OS X 10.9上使用pip安装Python图像库时出错
我想使用pip在Mavericks上安装PIL,但出现此错误。 _imagingft.c:73:10: fatal error: 'freetype/fterrors.h' file not found #include <freetype/fterrors.h> ^ 1 error generated. error: command 'cc' failed with exit status 1 我的命令行工具已安装并且是最新的,我发现的每个提示都无济于事。我该如何进行编译? 编辑:我刚刚检查过,freetype也已经通过自制软件安装了
78 python  macos  pip 

10
使用“设置”模块创建常量?
我对Python比较陌生。我希望创建一个“设置”模块,其中将存储各种特定于应用程序的常量。 这是我要设置代码的方式: settings.py CONSTANT = 'value' script.py import settings def func(): var = CONSTANT # do some more coding return var 我收到一条Python错误,指出: global name 'CONSTANT' is not defined. 我注意到在Django的源代码中,它们的settings.py文件具有与我一样命名的常量。我对如何将它们导入脚本并通过应用程序引用感到困惑。 编辑 感谢您的所有回答!我尝试了以下方法: import settings print settings.CONSTANT 我犯了同样的错误 ImportError: cannot import name CONSTANT
78 python 

3
一种类似于get()的用于检查Python属性的方法
如果我有字典,dict并且想检查一下,则dict['key']可以将其作为一个try块(非常好!),也可以使用get()方法False作为默认值。 我想为做同样的事情object.attribute。也就是说,False如果尚未设置对象,我已经有要返回的对象,但这给了我类似的错误 AttributeError:'bool'对象没有属性'attribute'

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.