my_var可以是None 时使用以下格式是不好的做法吗?
if my_var and 'something' in my_var:
#do something
Run Code Online (Sandbox Code Playgroud)
问题是'something' in my_var如果my_var为None ,则抛出TypeError.
或者我应该使用:
if my_var:
if 'something' in my_var:
#do something
Run Code Online (Sandbox Code Playgroud)
要么
try:
if 'something' in my_var:
#do something
except TypeError:
pass
Run Code Online (Sandbox Code Playgroud)
要重新解释这个问题,上面哪一项是Python中的最佳实践(如果有的话)?
欢迎替代方案!
我的想法:让线程在更新进度时发出QtSignal,触发一些更新进度条的功能.完成处理时也会发出信号,以便显示结果.
#NOTE: this is example code for my idea, you do not have
# to read this to answer the question(s).
import threading
from PyQt4 import QtCore, QtGui
import re
import copy
class ProcessingThread(threading.Thread, QtCore.QObject):
__pyqtSignals__ = ( "progressUpdated(str)",
"resultsReady(str)")
def __init__(self, docs):
self.docs = docs
self.progress = 0 #int between 0 and 100
self.results = []
threading.Thread.__init__(self)
def getResults(self):
return copy.deepcopy(self.results) …Run Code Online (Sandbox Code Playgroud) 所以我有一个大型数据库,我无法立即在内存中保存.我必须遍历表中的每个项目,处理它,并将处理后的数据放入表中的另一列.
当我循环我的光标时,如果我尝试运行更新语句,它会截断记录集(我相信因为它重新定位了游标对象).
问题:
创建第二个游标对象以运行更新语句是否允许我继续循环原始的select语句?
我是否需要与数据库建立第二个连接才能拥有第二个游标对象,这样我才能这样做?
sqlite如何响应与数据库的两个连接,一个从表中读取,另一个写入它?
我的代码(简化):
import sqlite3
class DataManager():
""" Manages database (used below).
I cut this class way down to avoid confusion in the question.
"""
def __init__(self, db_path):
self.connection = sqlite3.connect(db_path)
self.connection.text_factory = str
self.cursor = self.connection.cursor()
def genRecordset(self, str_sql, subs=tuple()):
""" Generate records as tuples, for str_sql.
"""
self.cursor.execute(str_sql, subs)
for row in self.cursor:
yield row
select = """
SELECT id, unprocessed_content
FROM data_table
WHERE processed_content IS NULL
"""
update = """
UPDATE data_table
SET …Run Code Online (Sandbox Code Playgroud) 问题:
我得到以下回溯,并不明白它的含义或如何解决它:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Python26\lib\multiprocessing\forking.py", line 342, in main
self = load(from_parent)
File "C:\Python26\lib\pickle.py", line 1370, in load
return Unpickler(file).load()
File "C:\Python26\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Python26\lib\pickle.py", line 1083, in load_newobj
obj = cls.__new__(cls, *args)
TypeError: object.__new__(pyodbc.Cursor) is not safe, use pyodbc.Cursor.__new__()
Run Code Online (Sandbox Code Playgroud)
情况:
我有一个SQL Server数据库,里面装满了要处理的数据.我正在尝试使用多处理模块来并行化工作并利用计算机上的多个核心.我的一般类结构如下:
work_queue和一个write_queuework_queue.work_queue并将完成的项目放入write_queue. …我花了几个小时搜索如何使用bsddb模块的例子,我发现的只有这些(从这里):
data = mydb.get(key)
if data:
doSomething(data)
#####################
rec = cursor.first()
while rec:
print rec
rec = cursor.next()
#####################
rec = mydb.set()
while rec:
key, val = rec
doSomething(key, val)
rec = mydb.next()
Run Code Online (Sandbox Code Playgroud)
有谁知道我在哪里可以找到更多(实用)如何使用这个包的例子?
或者有人会介意分享他们自己编写的使用它的代码吗?
编辑:
我之所以选择Berkeley DB,是因为它具有可扩展性.我正在对大约220万个网页进行潜在的语义分析.我对14个网页的简单测试产生了大约500,000条记录.所以做数学...我的表中将有大约78.6亿条记录.
如果有人知道我可以使用python访问的另一个高效,可扩展的数据库模型,请让我知道它!(lt_kije引起了我的注意,bsddb在Python 2.6中已弃用,并将在3.*中消失)
背景:
我正在清理大型(不能保留在内存中)制表符分隔的文件.当我清理输入文件时,我在内存中建立了一个列表; 当它获得1,000,000个条目(内存大约1GB)时,我将其排序(使用下面的默认密钥)并将列表写入文件.此类用于将已排序的文件重新组合在一起.它适用于我迄今遇到的文件.到目前为止,我最大的案例是合并66个已排序的文件.
问题:
示例数据:
这是其中一个文件中的一行的抽象:
'hash_of_SomeStringId\tSome String Id\t\t\twww.somelink.com\t\tOtherData\t\n'
外卖是我'SomeStringId'.lower().replace(' ', '')用作我的排序键.
原始代码:
class SortedFileMerger():
""" A one-time use object that merges any number of smaller sorted
files into one large sorted file.
ARGS:
paths - list of paths to sorted files
output_path - string path to desired output file
dedup - (boolean) remove lines with duplicate keys, default = True
key - use to override sort key, default = "line.split('\t')[1].lower().replace(' ', '')"
will be …Run Code Online (Sandbox Code Playgroud) 说我有一串话:'a b c d e f'.我想从这个字符串生成一个多字词的列表.
字顺序很重要.'f e d'不应从上面的例子中生成该术语.
编辑:此外,不应跳过单词. 'a c',或者'b d f'不应该生成.
我现在拥有的:
doc = 'a b c d e f'
terms= []
one_before = None
two_before = None
for word in doc.split(None):
terms.append(word)
if one_before:
terms.append(' '.join([one_before, word]))
if two_before:
terms.append(' '.join([two_before, one_before, word]))
two_before = one_before
one_before = word
for term in terms:
print term
Run Code Online (Sandbox Code Playgroud)
打印:
a
b
a b
c
b c
a b c
d
c …Run Code Online (Sandbox Code Playgroud) 我正在使用PyQt4用户界面.我已将stderr重定向到日志文件以便于调试和故障排除,但现在我需要在发生错误时向用户显示错误消息.
我的问题是我需要在发生异常时捕获异常并让用户知道它发生了,但仍然让回溯传播到stderr(即日志文件).
如果我做这样的事情:
def updateResults(self):
try:
#code that updates the results
except:
#display error message box
Run Code Online (Sandbox Code Playgroud)
这将捕获异常而不是传播到错误日志.
有没有办法向用户显示消息,然后继续传播错误?
这会有用吗?
except, e:
#display error message box
raise e
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来实现我的目标?
python error-handling error-logging exception-handling pyqt4
我是C#的新手,并试图找出字符串插入(即"some {0} string", toInsert),并遇到了一个我没想到的问题......
在您有两个构造函数的情况下:
public MyClass(String arg1) { ... }
public MyClass(String arg1, String arg2) { ... }
Run Code Online (Sandbox Code Playgroud)
我可以使用带有字符串插入的第一个构造函数吗?
...
toInsert = "def"
myClass = new MyClass("abc{0}ghi", toInsert)
...
Run Code Online (Sandbox Code Playgroud)
或者C#将此解释为第二个构造函数并将文字"abc{0}ghi"作为第一个参数传递?