Advertisement
DeaD_EyE

get clipboard a path with tkinter

Feb 8th, 2020
671
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. from pathlib import Path
  2. from tkinter import Tk, TclError
  3.  
  4.  
  5. def get_clipboard_as_path():
  6.     root = Tk()
  7.     root.withdraw()
  8.     try:
  9.         content = root.selection_get(selection="CLIPBOARD")
  10.     except TclError:
  11.         return None
  12.     finally:
  13.         root.destroy()
  14.  
  15.     file = Path(content)
  16.    
  17.     try:
  18.         if file.exists():
  19.             return file
  20.     except OSError:
  21.         pass
  22.    
  23.     return None
  24.  
  25.  
  26. # get the path
  27. my_path = get_clipboard_as_path()
  28. # my_path could be None
  29. if my_path:
  30.     print(f'The path is {my_path}')
  31.     # if my_path is a directory, find all python files
  32.     if my_path.is_dir():
  33.         print('The path is a directory')
  34.         for file in my_path.glob('*.py'):
  35.             print(file)
  36.     else:
  37.         print('The path is a file')
  38.         with my_path.open() as fd:
  39.             header = fd.readline()
  40.             print('First line:')
  41.             print(header)
  42. else:
  43.     print('It was not a Path, maybe a image or something else')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement