0

I am asking for your help. I would like to block the access and opening of a json file if it is already open and in use. I am testing by running my code twice and opening the same file twice. I would like that if one is not opened, at first that it does nothing. Afterwards, I would add a QDialog to warn the user

I was inspired by a post Check if a file is not open nor being used by another process

but it doesn't help me at all to block the access. From what I understood from the post, it's only to warn by a print that a file is already in progress

    self.name, _filtre = QtWidgets.QFileDialog.getOpenFileName(self.centralwidget, filter='*.json')


        with open(self.name) as file:
            for file in psutil.process_iter():
                    flist = file.open_files()
#if my file is already running, block acces
                    if flist:
                        raise FileExistsError

                    else :
                        self.dataTab = []
                        # Lecture du fichier
                        self.jsonlist = json.load(file)
                        self.site = self.jsonlist["site"]
                        self.user = self.jsonlist["user"]
                        self.project = self.jsonlist["project"]
                        self.dt_string = self.jsonlist["Date-Time"]

                        # dataTab récupère les valeurs dans la liste de la clé 'Test'
                        self.dataTab = self.jsonlist['Test']

my error :

Connected to pydev debugger (build 201.8743.20)
Traceback (most recent call last):
  File "C:\Users\station\PycharmProjects\asa_control\BAA_TESUT_ajoutASA.py", line 637, in open_project
    self.file_open()
  File "C:\Users\station\PycharmProjects\asa_control\BAA_TESUT_ajoutASA.py", line 661, in file_open
    self.jsonlist = json.load(file)
  File "C:\Users\station\anaconda3\envs\asa_station\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
AttributeError: 'Process' object has no attribute 'read'
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
AlexM
  • 1
  • 1
  • The error is quite clear... `file` is not a file. It is actually a process (`for file in psutil.process_iter():`). You probably need to use `flist` somehow instead (`flist = file.open_files()`) – Tomerikoo Jun 16 '22 at 12:52
  • Thank you, I was able to understand the error. But I don't really understand the solution, sorry, so I have to look at the current processes? Is my code base for my query correct? – AlexM Jun 20 '22 at 10:03

0 Answers0