Python教我们使用__enter__
和对对象进行清理__exit__
.如果我需要创建一个使用对象的对象,必须使用上下文管理器怎么办?想象一下:
from database1 import DB1
from database2 import DB2
Run Code Online (Sandbox Code Playgroud)
通常情况下,他们会这样使用:
with DB1() as db1, DB2() as db2:
db1.do_stuff()
db2.do_other_stuff()
Run Code Online (Sandbox Code Playgroud)
无论发生什么,db1
并db2
都将运行自己的__exit__
功能,并清理连接,同花顺等
当我把所有这些都放在课堂上时,我该怎么做?这是正确的吗?这显然是不正确的,正如评论中所指出的那样,上下文管理器db1
并db2
在块的末尾运行.
class MyApp(object):
def __enter__(self):
with DB1() as self.db1, DB2() as self.db2:
return self
def __exit__(self, type, value, traceback):
self.db1.__exit__(self, type, value, traceback)
self.db2.__exit__(self, type, value, traceback)
Run Code Online (Sandbox Code Playgroud)
我甚至考虑过做这样的事情:这看起来是个好主意,实际上(经过一些清理):
class MyApp(object):
def __init__(self):
self.db1 = DB1()
self.db2 = DB2()
def __enter__(self):
self.db1.__enter__()
self.db2.__enter__()
return …
Run Code Online (Sandbox Code Playgroud) 根据另一个问题,我一直在做这个(python)将我的时间戳推入bigquery(它们来自nr-of-miliseconds格式的node-js应用程序):
e["createdOn"] = e["createdOn"] / 1000.0
Run Code Online (Sandbox Code Playgroud)
但他们最终是这样的:
SELECT updatedOn,TIMESTAMP_TO_USEC(updatedOn) FROM [table.sessions] WHERE session = xxxxxxx
Row updatedOn f0_
1 2014-08-18 11:55:49 UTC 1408362949426000
2 2014-08-18 11:55:49 UTC 1408362949426000
Run Code Online (Sandbox Code Playgroud)
我一直在打印调试信息,这是他们在插入insertAll之前的最后一个表单:
{u'session': 100000000000080736, u'user': 1000000000075756, u'updatedOn': 1409052076.223}
Run Code Online (Sandbox Code Playgroud) 我有一个测试用例,其中用户关闭浏览器并重新打开它,以测试某些登录 cookie 是否已正确加载。
browser.get("domain1.com")
cookies_domain1 = browser.get_cookies()
browser.get("domain2.com")
cookies_domain2 = browser.get_cookies()
//close browser
//re-open browser
browser.get("domain1.com")
for cookie in cookies_domain1:
driver.add_cookie(cookie)
browser.get("domain2.com")
for cookie in cookies_domain2:
driver.add_cookie(cookie)
Run Code Online (Sandbox Code Playgroud)
但这看起来不太好。我需要在打开页面之前加载cookie。Selenium 似乎只允许将 cookie 从一个页面添加到该页面!
我尝试执行此操作的另一种方法是保存browser.profile.path
目录,备份它,然后在重新连接时将其传递给 a FirefoxProfile
,该目录将传递给 a webdriver.Firefox(FirefoxProfile(path_to_directory_backup))
。不幸的是,这似乎并没有保存cookie。
我有一些像这样的代码:
class Person(object):
def drive(self, f, t):
raise NotImplementedError
class John(Person):
def drive(self, f, t):
print "John drove from %s to %s" % (f,t)
class Kyle(Person):
def drive(self, f, t):
print "Kyle drove from %s to %s" % (f,t)
class RandomPerson(Person):
# instansiate either John or Kyle, and inherit it.
pass
class Vehicle(object):
pass
class Driver(Person, Vehicle):
def __init__(self):
# instantiate and inherit a RandomPerson somehow
pass
d1 = Driver()
d1.drive('New York', 'Boston')
>>> "John drove from New York to …
Run Code Online (Sandbox Code Playgroud) 从手册:
random.seed([X])
初始化基本随机数生成器.可选参数x可以是任何可哈希的对象.如果省略x或None,则使用当前系统时间; 当前系统时间也用于在首次导入模块时初始化生成器.如果操作系统提供随机源,则使用它们而不是系统时间(有关可用性的详细信息,请参阅os.urandom()函数).
如果给出可清洗对象,则仅在禁用PYTHONHASHSEED时确保确定性结果.
user@MacBook:~$ python
Python 2.7.11 (default, Aug 6 2016, 02:11:50)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> r = random.Random('somelongstring' * 40)
>>> r.randint(1, 1000)
332
>>> exit()
user@MacBook-Pro:~$ python
Python 2.7.11 (default, Aug 6 2016, 02:11:50)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> r = …
Run Code Online (Sandbox Code Playgroud) 我有一个3-4个参数的解析器,效果很好.我想为脚本提供未知数量的额外参数,这些参数将被加载到模板中.我已经阅读了argparse文档,但我不确定它是否可行.我可以parse_known_arguments()
,但我仍然需要自己处理["--placeholder1", "value1", "--placeholder2", "value2", ...]
数组.我应该继续这样做,还是有更多的pythonic方式?
就在我的头顶:
parser = argparse.ArgumentParser()
parser.add_argument("--template", required=True)
parser.add_argument("--location", required=True)
args,unknown = parser.parse_known_arguments()
tpl = LoadTemplate(args.template)
# Missing part where I transform unknown into an dict or namespace called extraarguments
raw = tpl.render(extraarguments)
# Print into args.location raw
render.py --template template1 --location /path/to/invoices --author John --customer Customer1 --title "Your invoice is ready!"
render.py --template template2 --location /path/to/newsletter --customer Customer2 --sender john@store.com --subject "Weekly newsletter"
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,template
并且location
必须存在,但额外的参数应该是解压缩并送入模板渲染功能.它看起来像一个单行,但是有更多的pythonic方式吗?
python ×6
python-2.7 ×4
argparse ×1
class ×1
cookies ×1
factory ×1
firefox ×1
google-api ×1
inheritance ×1
random ×1
selenium ×1