Find processes with the specific port open as a file handle. Note: On Windows, this function skips the open_files() check because it's extremely slow and can hang. COM ports don't typically show up as file handles anyway. This function returns empty list on Windows. Returns:
(
port_name: str,
)
| 127 | |
| 128 | |
| 129 | def find_processes_with_open_files( |
| 130 | port_name: str, |
| 131 | ) -> list[tuple[psutil.Process, list[str]]]: |
| 132 | """Find processes with the specific port open as a file handle. |
| 133 | |
| 134 | Note: On Windows, this function skips the open_files() check because it's |
| 135 | extremely slow and can hang. COM ports don't typically show up as file |
| 136 | handles anyway. This function returns empty list on Windows. |
| 137 | |
| 138 | Returns: |
| 139 | List of tuples (process, list of open file paths matching port) |
| 140 | """ |
| 141 | results: list[tuple[psutil.Process, list[str]]] = [] |
| 142 | |
| 143 | # Skip on Windows - open_files() is too slow and COM ports don't show as files |
| 144 | import platform |
| 145 | |
| 146 | if platform.system() == "Windows": |
| 147 | return results |
| 148 | |
| 149 | port_lower = port_name.lower() |
| 150 | |
| 151 | for proc in psutil.process_iter(["pid", "name"]): |
| 152 | try: |
| 153 | open_files = proc.open_files() |
| 154 | matching_files = [ |
| 155 | f.path for f in open_files if port_lower in f.path.lower() |
| 156 | ] |
| 157 | if matching_files: |
| 158 | results.append((proc, matching_files)) |
| 159 | except (psutil.NoSuchProcess, psutil.AccessDenied, AttributeError): |
| 160 | # Some processes don't have open_files() or access is denied |
| 161 | pass |
| 162 | |
| 163 | return results |
| 164 | |
| 165 | |
| 166 | def diagnose_port(port_name: str) -> None: |