是否可以使用withPython中的语句声明多个变量?
就像是:
from __future__ import with_statement
with open("out.txt","wt"), open("in.txt") as file_out, file_in:
for line in file_in:
file_out.write(line)
Run Code Online (Sandbox Code Playgroud)
......还是正在清理两个资源同时出现问题?
我想循环遍历文本文件的内容,并在某些行上进行搜索和替换,并将结果写回文件.我可以先将整个文件加载到内存中然后再写回来,但这可能不是最好的方法.
在以下代码中,最好的方法是什么?
f = open(file)
for line in f:
if line.contains('foo'):
newline = line.replace('foo', 'bar')
# how to write this newline back to the file
Run Code Online (Sandbox Code Playgroud) 在Python 2.6中,我们使用以下方式格式化嵌套上下文管理器:
with nested(
context1,
context2
) as a, b:
pass
Run Code Online (Sandbox Code Playgroud)
从Python 2.7开始,nested不推荐使用.我在一行上看到了很多关于多个上下文管理器的例子,但我找不到允许它们在多行上的语法.你会怎么做?
# That's working fine
with context1 as a, context2 as b:
pass
# But how do we make it multine?
# These are not working
with (
context1,
context2
) as a, b:
pass
with context1 as a,
context2 as b:
pass
Run Code Online (Sandbox Code Playgroud) 注意:我知道
with open('f1') as f1, open('f2') as f2:
...
Run Code Online (Sandbox Code Playgroud)
句法.这是一个不同的问题.
给定一个字符串列表file_names有一种方法可以使用with/ as打开每个文件名,使用一行.像这样的东西:
with [open(fn) for fn in file_names] as files:
# use the list of files
Run Code Online (Sandbox Code Playgroud)
这当然不起作用,因为它试图在列表上使用上下文管理器.在运行时之前可能无法知道列表的长度,例如sys.argv[1:]
似乎是在敲我的新手错误,我不是新手.我有一个1.2G已知良好的zipfile'train.zip',其中包含一个3.5G文件'train.csv'.我打开zip文件和文件本身没有任何例外(没有LargeZipFile),但生成的文件流似乎是空的.(UNIX'unzip -c ...'确认它很好)Python ZipFile.open()返回的文件对象不可搜索或者无法检测,所以我无法检查.
Python发行版是2.7.3无EPD 7.3-1(32位) ; 但对于大拉链应该没问题.操作系统是MacOS 10.6.6
import csv
import zipfile as zf
zip_pathname = os.path.join('/my/data/path/.../', 'train.zip')
#with zf.ZipFile(zip_pathname).open('train.csv') as z:
z = zf.ZipFile(zip_pathname, 'r', zf.ZIP_DEFLATED, allowZip64=True) # I tried all permutations
z.debug = 1
z.testzip() # zipfile integrity is ok
z1 = z.open('train.csv', 'r') # our file keeps coming up empty?
# Check the info to confirm z1 is indeed a valid 3.5Gb file...
z1i = z.getinfo(file_name) …Run Code Online (Sandbox Code Playgroud) 我经常需要用别的东西临时切换一个变量的值,做一些依赖于这个变量的计算,然后将变量恢复到它的原始值。例如:
var = 0
# Assign temporary value and do computation
var_ori = var
var = 1
do_something_with_var() # Function that reads the module level var variable
# Reassign original value
var = var_ori
Run Code Online (Sandbox Code Playgroud)
这似乎是使用上下文管理器(with语句)的明显机会。Python 标准库是否包含任何这样的上下文管理器?
我知道这种事情通常由其他更好的方法处理,而不是临时更改变量。然而,我并不是要求明显的解决方法。
在我的实际工作案例中,我无法更改该do_something_with_var功能。实际上,这甚至不是一个函数,而是作为元编程的一部分在全局命名空间上下文中求值的一串代码。我给出的例子是我能想到的最简单的例子,它使我的问题与临时变量有关。我没有要求获得我的示例代码的解决方法(正确版本),而是要求获得我书面问题的答案。
我正在尝试使用fileinput模块的就地过滤功能来就地重写输入文件。
需要将编码(用于读写)设置为latin-1并尝试传递openhook=fileinput.hook_encoded('latin-1')给它,fileinput.input但由于错误而受阻
ValueError: FileInput cannot use an opening hook in inplace mode
Run Code Online (Sandbox Code Playgroud)
仔细检查后,我发现fileinput文档中明确说明了这一点:不能同时使用就位和openhook
我该如何解决?
我模块的结构:
foo:
- load() # from DB
bar:
- check() # with user
- take_action()
Run Code Online (Sandbox Code Playgroud)
我想通过模拟加载和检查来测试take_action(它在执行操作之前基本上加载值并检查用户).
这是嘲笑:
mock_load = Mock(side_effects=[<>, <>, <>]) # different data sets
mock_check = Mock(return_value=True) # User approval
Run Code Online (Sandbox Code Playgroud)
我如何使用patch.multiple来实现这一目标?
with patch.multiple(??):
# proceed to test
take_action
Run Code Online (Sandbox Code Playgroud) 我正在尝试自学Python的异步功能.为此,我构建了一个异步Web scraper.我想限制我一次打开的连接总数,以成为服务器上的好公民.我知道信号量是一个很好的解决方案,并且asyncio库内置了一个信号量类.我的问题是,当你在组合和语法yield from中使用async函数时,Python会抱怨.以下是我正在使用的确切语法...yieldawait
import asyncio
import aiohttp
sema = asyncio.BoundedSemaphore(5)
async def get_page_text(url):
with (yield from sema):
try:
resp = await aiohttp.request('GET', url)
if resp.status == 200:
ret_val = await resp.text()
except:
raise ValueError
finally:
await resp.release()
return ret_val
Run Code Online (Sandbox Code Playgroud)
提出这个例外:
File "<ipython-input-3-9b9bdb963407>", line 14
with (yield from sema):
^
SyntaxError: 'yield from' inside async function
Run Code Online (Sandbox Code Playgroud)
我能想到的一些可能的解决方案......
@asyncio.coroutine装饰器我是Python的异步功能的新手,所以我可能会遗漏一些明显的东西.
我有一个情况,我有几个项目,我想用with块打开.在我的情况下,这些是外部硬件设备,在关闭时需要进行一些清理 - 但这对于手头的要点并不重要.
假设一个类是这样的:
class Controller(object):
def __init__(self, name):
self._name = name
def __enter__(self):
# Do some work on entry
print("Entering", self._name)
return self
def __exit__(self, type, value, traceback):
# Clean up (restoring external state, turning off hardware, etc)
print("Exiting", self._name)
return False
def work(self):
print("Working on", self._name)
Run Code Online (Sandbox Code Playgroud)
我会(给定一定数量的Controllers),做类似的事情
with Controller("thing1") as c1:
with Controller("thing2") as c2:
c1.do_work()
c2.do_work()
Run Code Online (Sandbox Code Playgroud)
但是,我遇到过这样一种情况:我需要以这种方式管理一些灵活的事情.也就是说,我的情况类似于:
things = ["thing1", "thing2", "thing3"] # flexible in size
for thing in things:
with Controller(thing) as …Run Code Online (Sandbox Code Playgroud) 似乎对象清理是我在编程期间遇到的一个非常常见的问题。迄今为止,我一直with按照此处的建议使用该语句
我今天有另一个想法,对我来说似乎更优雅(因为它不需要最终用户的 with 语句)。这个想法是对某种类型的对象使用 try-finally 装饰器(有一个清理方法)。
只是想知道这种做法是否有问题,或者是否有更好的方法。我不喜欢我的许多类需要使用 with 语句进行初始化,但我也想确保我的对象正确关闭。这是一个简短的例子。
def cleanme(func):
def _decorator(self, *args, **kwargs):
try:
func(self, *args, **kwargs)
finally:
self._cleanup()
return _decorator
class IObject(object):
def __init__(self):
self.file_name = "some_file.txt"
self._file_object = None
self._cleaned = True
@cleanme
def run(self):
self._connect()
while True:
# do some things over a long period
pass
def _connect(self):
self._file_object = open(self.file_name)
self._cleaned = False
def _cleanup(self):
if not self._cleaned:
self._file_object.close()
self._cleaned = True
Run Code Online (Sandbox Code Playgroud) 我倾向于经常使用Python"with"语句.在我将一些文件符号链接或复制到目录后,主要用于清理目录,因为即使python脚本崩溃,任务仍然会执行.以下是我的函数的示例,可以与"with"语句一起使用.
@contextmanager
def use_symlink(orig, dest):
os.symlink(orig, dest)
try:
yield
finally:
os.unlink(link)
Run Code Online (Sandbox Code Playgroud)
我使用这些语句的方式很快就会堆积起来.
#Off to an adventure
with use_symlink(a, b):
with use_symlink(c, b):
with use_symlink(d, b):
with working_dir(dir1):
#do something
with working_dir(dir2):
#do something that creates file dir2_file1, dir2_file2
with use_symlink(dir2_file1, b):
with use_symlink(dir2_file2, b):
with working_dir(b):
#Do the last thing
#Home safely
Run Code Online (Sandbox Code Playgroud)
是否有更好的方法来执行上述操作与强大的"with"语句相同的简易性和安全性?
python ×12
python-3.x ×2
class ×1
decorator ×1
encoding ×1
file ×1
file-io ×1
file-type ×1
python-2.7 ×1
python-3.2 ×1
python-3.5 ×1
python-3.6 ×1
semaphore ×1
unit-testing ×1
zipfile ×1