Repository navigation
Expand file tree
/
Copy pathclipboard_utils.py
More file actions
56 lines (47 loc) · 1.66 KB
/
Copy pathclipboard_utils.py
File metadata and controls
56 lines (47 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import os
import subprocess
from PyQt6.QtCore import QMimeData, QUrl
from PyQt6.QtWidgets import QApplication
def copy_file_to_clipboard(filepath):
"""
Copies a file to the clipboard using PowerShell.
This mimics the behavior of selecting a file in Explorer and pressing Ctrl+C.
Fallback to Qt's clipboard mechanism if PowerShell fails.
"""
filepath = os.path.abspath(filepath)
if not os.path.exists(filepath):
return False, "File does not exist"
# Strategy 1: PowerShell (Native / Robust)
# Set-Clipboard -Path "..." mimics Explorer copy perfectly.
try:
cmd = [
"powershell",
"-NoProfile",
"-NonInteractive",
"-Command",
f"Set-Clipboard -Path '{filepath}'"
]
# subprocess.run ensures we wait for it to finish
result = subprocess.run(
cmd,
capture_output=True,
text=True,
check=False,
creationflags=subprocess.CREATE_NO_WINDOW,
)
if result.returncode == 0:
return True, "Copied via PowerShell"
else:
print(f"PowerShell Clipboard Error: {result.stderr}")
# Don't return yet, try Strategy 2
except Exception as e:
print(f"PowerShell execution failed: {e}")
# Strategy 2: Qt (Fallback)
try:
data = QMimeData()
url = QUrl.fromLocalFile(filepath)
data.setUrls([url])
QApplication.clipboard().setMimeData(data)
return True, "Copied via Qt (Fallback)"
except Exception as e:
return False, f"All methods failed. Qt Error: {e}"