Wie kann ich Benutzer warnen, wenn bestimmte Bibliotheken importiert werden?Python

Python-Programme
Guest
 Wie kann ich Benutzer warnen, wenn bestimmte Bibliotheken importiert werden?

Post by Guest »

Ich möchte den Benutzer warnen, wenn bestimmte Bibliotheken importiert werden.

Code: Select all

import sys
import warnings

class ImportWarningHandler:
def __init__(self, libraries_to_warn):
self.libraries_to_warn = set(libraries_to_warn)  # Use a set for efficient lookups

def find_spec(self, fullname, path, target=None):
if fullname in self.libraries_to_warn:
warnings.warn(
f"Warning: The library '{fullname}' is imported. Use it cautiously!",
ImportWarning
)
return None

warnings.simplefilter("default", ImportWarning)

libraries_to_warn = ["numpy", "pandas", "tensorflow"]
sys.meta_path.insert(0, ImportWarningHandler(libraries_to_warn))

import numpy
import pandas

print('something')

import numpy  #Assuming from a circular import #No warnings
Ausgabe:

Code: Select all

Warning (from warnings module):
File "C:\Users\Bhargav\Desktop\ss.py", line 10
warnings.warn(
ImportWarning: Warning: The library 'numpy' is imported. Use it cautiously!

Warning (from warnings module):
File "C:\Users\Bhargav\Desktop\ss.py", line 10
warnings.warn(
ImportWarning: Warning: The library 'pandas' is imported. Use it cautiously!
something
In einem meiner Projekte habe ich zirkuläre Importe. Mein Code schlägt in solchen Szenarien fehl. Vermisse ich etwas? Ist das übertrieben? Warum kann Python meinen Numpy-Import nicht erkennen, wenn ich ihn ein zweites Mal durchgeführt habe?
Das funktioniert so,

Code: Select all

import numpy

del numpy

print('something')

import numpy  #Assuming from a circular import #works

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post