我有以下代码:
import os
import sys
import tempfile
import subprocess
with tempfile.NamedTemporaryFile('w+') as f:
if sys.platform == 'linux':
subprocess.call('vim', f.name)
elif sys.platform == 'nt':
os.system(f.name)
它在 Linux 上使用 vim
或在 Windows 上使用默认编辑器打开 foobar.txt
。在 Linux 上运行良好:tempfile.NamedTemporaryFile()
创建一个临时文件,vim
打开它。然而,在 Windows 上,系统说:
The process cannot access the file because it is being used by another process.
我猜那是因为脚本当前正在使用该文件。
为什么它可以在 Linux 上运行,我如何让它在 Windows 上运行?
最佳答案
我以前遇到过这个问题。我的问题是我必须写入一个文件,然后将该文件的名称用作命令中的参数。
这在 Linux 中起作用的原因是,作为 @PM 2Ring评论里说,Linux允许多个进程写入同一个文件,Windows却不允许。
有两种方法可以解决这个问题。
一个是创建一个temporary directory并在该目录中创建一个文件。
# Python 2 and 3
import os
import tempfile
temp_dir = tempfile.mkdtemp()
try:
temp_file = os.path.join(temp_dir, 'file.txt')
with open(temp_file, 'w') as f:
pass # Create the file, or optionally write to it.
try:
do_stuff(temp_file) # In this case, open the file in an editor.
finally:
os.remove(file_name)
finally:
os.rmdir(temp_dir)
# Python 3 only
import tempfile
with tempfile.TemporaryDirectory() as temp_dir:
temp_file = os.path.join(temp_dir, 'file.txt')
with open(temp_file, 'w') as f:
pass # Create the file, or optionally write to it.
do_stuff(temp_file)
# with tempfile.TemporaryDirectory(): automatically deletes temp_file
另一种方法是使用 delete=False
创建临时文件,这样当您关闭它时,它不会被删除,然后稍后手动删除它。
# Python 2 and 3
import os
import tempfile
fp = tempfile.NamedTemporaryFile(suffix='.txt', delete=False)
try:
fp.close()
do_stuff(fp.name)
finally:
os.remove(fp.name)
这是一个可以生成文件的小上下文管理器:
import os
import tempfile
_text_type = type(u'')
class ClosedTemporaryFile(object):
__slots__ = ('name',)
def __init__(self, data=b'', suffix='', prefix='tmp', dir=None):
fp = tempfile.mkstemp(suffix, prefix, dir, isinstance(data, _text_type))
self.name = fp.name
if data:
try:
fp.write(data)
except:
fp.close()
self.delete()
raise
fp.close()
def exists(self):
return os.path.isfile(self.name)
def delete(self):
try:
os.remove(self.name)
except OSError:
pass
def open(self, *args, **kwargs):
return open(self.name, *args, **kwargs)
def __enter__(self):
return self.name
def __exit__(self, exc_type, exc_val, exc_tb):
self.delete()
def __del__(self):
self.delete()
用法:
with ClosedTemporaryFile(suffix='.txt') as temp_file:
do_stuff(temp_file)
关于python - 在脚本中打开文件时在编辑器中打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34650576/