【问题标题】:python: problem using call.subprocess to use a file after writing itpython:使用call.subprocess在写入文件后使用文件的问题
【发布时间】:2009-03-11 19:14:37
【问题描述】:

在 python 中,我正在尝试编写一个脚本来编辑文本文件,然后运行使用这些文本文件的可执行文件。它基本上需要 1)打开和读取/写入文本文件,以及 2)使用我刚刚在 bash 命令中编写的文件。这是一个简单的例子:

import subprocess

# write file
a = ['1\n','2\n','3\n','4\n','5th and final line']
f = open('junk01.txt', 'wb')
f.writelines(a)
f.close

# show file
subprocess.call('cat junk01.txt', shell=True)

由于某种原因,subprocess.call 命令没有显示 junk01.txt 文件的内容。但是,在我运行此代码并在 bash 中键入 cat junk01.txt 后,文件已正确写入。同样,我发现在我打开、写入和关闭一个文本文件,然后尝试在可执行文件中使用它之后,该文件还没有被写入。关于为什么会这样以及我可以做些什么来解决它的任何解释?

【问题讨论】:

    标签: python subprocess


    【解决方案1】:

    通过实际调用 close() 方法来关闭文件。这将隐式地将缓冲区刷新到磁盘。

    f.close()
    

    而不是

    f.close     #this probably doesn't do anything, but if there was no close method it would raise an error.
    

    【讨论】:

    • 这就是我的全部问题吗?哇,我感觉自己像个白痴。我试了一下,果然,它有效。这就是我尝试用我上周刚开始学习的语言做一些复杂的事情所得到的……谢谢!
    • 在我应该“更好地了解”多年之后,忘记刷新输出让我感到困惑 - 我觉得这是一个常见错误。
    • f.close 确实做了一些事情。我定位close方法函数。不评估它,但它至少找到它。
    【解决方案2】:

    虽然第一个答案绝对正确且正确,但您也可以将 f 设置为 None 而不是按如下方式完成:

    import subprocess
    
    # write file
    a = ['1\n','2\n','3\n','4\n','5th and final line\n']
    f = open('junk01.txt', 'wb')
    f.writelines(a)
    f = None
    # show file
    subprocess.call('cat junk01.txt', shell=True)
    

    ~

    将 f 设置为 None 会使变量停止服务并导致文件被隐式关闭而不是被显式关闭(如第一个首选示例) 我不提倡这种写代码的方式,因为它有点草率,我只是提到它作为一种替代解决方案。

    [centos@localhost ~/test/stack]$  python 1.py
    1
    2
    3
    4
    5th and final line
    [centos@localhost ~/test/stack]$  
    

    【讨论】:

      猜你喜欢
      • 2014-06-20
      • 2013-04-18
      • 1970-01-01
      • 2021-10-18
      • 2021-11-27
      • 1970-01-01
      • 2011-09-15
      • 1970-01-01
      • 2021-05-07
      相关资源
      最近更新 更多