【问题标题】:Batch file not closed after being created and written to by Python?批处理文件在被Python创建和写入后没有关闭?
【发布时间】:2018-12-13 20:07:33
【问题描述】:

我的代码基本上创建了一个.bat 文件,在其上写入一些文本,然后使用Popen 运行它。但我得到这个错误:

PermissionError: [WinError 32] 该进程无法访问该文件,因为它正被另一个进程使用

这是我得到的:

def killProcesses(self):
    processlist = open("processes.txt")
    with open("kill.bat", "w") as batfile:
        batfile.write("""echo off
cls
""")
    batfile.close()
    for line in processlist:
        newbatfile = open("kill.bat","a")
        newdata = line.replace('\n','')
        newbatfile.write("""
Taskkill /IM """+newdata+""" /F""")
    p = Popen("kill.bat")
    stdout,stderr = p.communicate()
    processlist.close()

我做了一些研究,发现在我的代码中添加 withclose() 可能会解决问题,但它什么也没做,我仍然收到错误消息。难道我做错了什么?我的猜测是我没有指定确切的文件路径,但是该文件与 python 脚本位于同一目录中,所以我觉得好像我不需要指定确切的路径。任何帮助将不胜感激。

【问题讨论】:

  • 你没有关闭newbatfile

标签: python python-3.x batch-file subprocess popen


【解决方案1】:

您最初的 batfile.close() 调用是不必要的:with 块确保文件在退出块时关闭。但是,您以后的循环会在每次通过循环时打开文件的新句柄,并且永远不会关闭它们。您可以考虑将循环重写为:

with open("kill.bat", "a") as newbatfile:
    for line in processlist:
        newdata  = line.replace("\n", "")
        newbatfile.write(...)

或者更好的是,只需将循环放在原始块中即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多