下面是我的my_create方法的示例,以及使用该方法的示例.
@contextmanager
def my_create(**attributes):
obj = MyObject(**attributes)
yield obj
obj.save()
with my_create(a=10) as new_obj:
new_obj.b = 7
new_obj.a # => 10
new_obj.b # => 7
new_obj.is_saved() # => True
Run Code Online (Sandbox Code Playgroud)
对Ruby/Rails的用户来说,这可能看起来很熟悉.它类似于ActiveRecord::create方法,with块内的代码就像一个块一样.
然而:
with my_create(a=10) as new_obj:
pass
new_obj.a # => 10
new_obj.is_saved() # => True
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,我将一个空的"块"传递给了我的my_create函数.事情按预期工作(my_obj已初始化并保存),但格式看起来有点不稳定,并且with块似乎没有必要.
我宁愿能够my_create直接打电话,而不必设置passing with块.不幸的是,我当前的实现不可能my_create.
my_obj = create(a=10)
my_obj # => <contextlib.GeneratorContextManager at 0x107c21050>
Run Code Online (Sandbox Code Playgroud)
我不得不呼吁双方__enter__并__exit__在 …
基于对象的真实性,转换为布尔值的最pythonic方法是什么?
return bool(an_object)
要么
if an_object:
return True
else:
return False
Run Code Online (Sandbox Code Playgroud)
或完全不同的东西?
在这种情况下,我们无法依靠对象的真实性.
假设您在 python 解释器中输入了以下内容:
from urllib import request
from bs4 import BeautifulSoup
soup = BeautifulSoup(request.urlopen("http://en.wikipedia.org/wiki/Python_(programming_language)").read())
a = soup.find_all('p')
b = a.find_all('href')
Run Code Online (Sandbox Code Playgroud)
我希望 b 是段落中所有链接的列表,但是,它给出了一个属性错误,其中 a 是“ResultSet”并且没有属性“find_all”。如何使用 BeautifulSoup 找到段落中的所有链接?
在下面的示例代码中,我们打开一个文件描述符到sandbox.log,将它作为stdout提供给子进程,然后关闭文件描述符,但子进程仍然可以写入该文件.是subprocess.Popen在内部复制文件描述符吗?将文件描述符传递给子进程后关闭它是否安全?
import subprocess
import os
import time
print 'create or clear sandbox.log'
subprocess.call('touch sandbox.log', shell=True)
subprocess.call('echo "" > sandbox.log', shell=True)
print 'open the file descriptor'
fd = os.open('sandbox.log', os.O_WRONLY)
command = 'sleep 10 && echo "hello world"'
print 'run the command'
p = subprocess.Popen(command, stdout=fd, stderr=subprocess.STDOUT, shell=True)
os.close(fd)
try:
os.close(fd)
except OSError:
print 'fd is already closed'
else:
print 'fd takes some time to close'
if p.poll() is None:
print 'p isnt finished, but fd is closed'
p.wait()
print 'p …Run Code Online (Sandbox Code Playgroud)