【问题标题】:Python reading from tempfile not successfulPython 从临时文件读取不成功
【发布时间】:2015-01-21 13:09:29
【问题描述】:
with tempfile.NamedTemporaryFile(delete = False) as tmpfile:
    subprocess.call(editor + [tmpfile.name])    # editor = 'subl -w -n' for example 
    tmpfile.seek(0)
    print tmpfile.read()

... 打开我的 Sublime Text,但是当我输入一些内容并关闭文件时,我没有得到任何输出或错误,只有一个空行(在 Python 2 上)。是的,程序会等到我写完。

编辑:
我刚刚发现这可能是Sublime Text 特有的问题,因为viemacsnano 在作为编辑器输入时都可以正常工作。 但我仍然想知道如何解决这个问题。

【问题讨论】:

  • 编辑器是字符串吗?在这种情况下,子进程调用本身会失败,因为您将一起添加字符串和列表
  • 其实就是一个列表。

标签: python subprocess readfile temporary-files


【解决方案1】:

根据“编辑”部分,您可以保存文件然后重新打开它,这可能不是最好的解决方案,也不能“解决”原始问题,但至少它应该可以工作:

import subprocess
import tempfile

editor = ['gedit']

with tempfile.NamedTemporaryFile(delete=False) as tmpfile:
    subprocess.call(editor + [tmpfile.name])    # editor = 'subl -w -n' for example 
    tmpfile.file.close()
    tmpfile = file(tmpfile.name)
    print tmpfile.read()

【讨论】:

    【解决方案2】:

    就像直接写入输出文件一样工作:

    #!/usr/bin/env python
    import subprocess
    import sys
    import tempfile
    
    editor = [sys.executable, '-c', "import sys;"
                                    "open(sys.argv[1], 'w').write('abc')"]
    with tempfile.NamedTemporaryFile() as file:
        subprocess.check_call(editor + [file.name])
        file.seek(0)
        print file.read() # print 'abc'
    

    如果编辑器先写入自己的临时文件并在最后重命名它会失败:

    #!/usr/bin/env python
    import subprocess
    import sys
    import tempfile
    
    editor = [sys.executable, '-c', r"""import os, sys, tempfile
    output_path = sys.argv[1]
    with tempfile.NamedTemporaryFile(dir=os.path.dirname(output_path),
                                     delete=False) as file:
        file.write(b'renamed')
    os.rename(file.name, output_path)
    """]
    with tempfile.NamedTemporaryFile() as file:
        subprocess.check_call(editor + [file.name])
        file.seek(0)
        print file.read() #XXX it prints nothing (expected 'renamed')
    

    @Vor suggested 重新打开文件有帮助:

    #!/usr/bin/env python
    import os
    import subprocess
    import sys
    import tempfile
    
    editor = [sys.executable, '-c', r"""import os, sys, tempfile
    output_path = sys.argv[1]
    with tempfile.NamedTemporaryFile(dir=os.path.dirname(output_path),
                                     delete=False) as file:
        file.write(b'renamed')
    os.rename(file.name, output_path)
    """]
    try:
        with tempfile.NamedTemporaryFile(delete=False) as file:
            subprocess.check_call(editor + [file.name])
        with open(file.name) as file:
            print file.read() # print 'renamed'
    finally:
        os.remove(file.name)
    

    【讨论】:

      猜你喜欢
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多