【问题标题】:How to close .csv file that was opened outside of the script?如何关闭在脚本之外打开的 .csv 文件?
【发布时间】:2018-04-17 02:26:42
【问题描述】:

我目前正在使用 Raspian OS 和 Libre Office。我正在使用 Python 3。 我正在尝试创建一个 RFID 门锁来记录每个进入的用户。

我遇到的问题是,如果有人在查看日志后打开 .csv 文件,我的脚本将无法写入。所以它会抛出一个错误。我希望我的脚本在打开该文件的情况下关闭当前打开的实例(窗口),然后我可以打开脚本并写入文件。

该文件与我的 python 脚本位于同一文件夹中。

我试过了:

os.system("TASKKILL /IM Entry_Log.csv")

没有运气。

这是我现在拥有的功能。我需要在我的异常声明中关闭该文件。

def unlockDoor(x):
    #Add GPIO Output here later
    while True:
        try:
            userDictionary = shelve.open("User_Dictionary")
            print('Welcome,', userDictionary[x])
            print('Door Unlocked')
            with open("Entry_Log.csv", "a") as log:
                log.write("{0},{1},{2}\n".format(time.strftime("%Y-%m-%d %H:%M:S"), x, userDictionary[x]))
            userDictionary.close()
        except:
            #close the open window for "Entry_Log.csv" here <--

【问题讨论】:

  • 我很确定 TASKKILL 是一个 Windows 命令行命令,而不是一个 linux 命令。您可以尝试使用 linux 等效命令
  • 好的,搜索等效项。有谁知道这个等价物可能是什么?
  • pkill 我猜
  • 我为pkill 看到的所有内容都建议停止其他python 脚本,而不是关闭文件。
  • os.kill(pid,sig) 怎么样。不确定 pid 和 sig 需要是什么

标签: python python-3.x file window


【解决方案1】:

以下代码在 Linux 上适用于我,使用 psutil 包。当文件无法打开时,将搜索所有其他打开该文件的进程,并向这些进程发送终止信号。

注意,这仅在调用进程具有正确权限时才有效。

import psutil
import sys
import os
import signal

def terminate_others(pattern):
    pids = psutil.pids();
    for pid in pids:
        p = psutil.Process(pid)
        try:
            flist = p.open_files()
            if flist:
                for f in flist:
                    if pattern in f.path:
                        print "Terminating " + repr(pid)
                        os.kill(pid, signal.SIGTERM)
        except:
            pass


fname = "Entry_Log.csv"

try:
    with open(fname, "a") as log:
        log.write("Some log text")
except:
    print "error:", sys.exc_info()[0]
    # close other processes that have this file open
    terminate_others(fname)

希望这会有所帮助。

【讨论】:

  • 我一定会试试这个并尽快回复你
猜你喜欢
  • 1970-01-01
  • 2014-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-22
  • 2013-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多