Python调用PowerShell复制文件到剪贴板失败问题排查
文件复制到剪贴板的问题解决
问题原因
[System.Windows.Forms.Clipboard]属于Windows Forms程序集,PowerShell默认不会自动加载这个程序集,所以直接调用会提示“找不到类型”。而dir、Get-Process这类基础命令属于PowerShell核心模块,无需额外加载就能运行。
解决方法
1. 先加载Windows Forms程序集
在执行剪贴板操作前,必须先加载对应的程序集,PowerShell命令如下:
Add-Type -AssemblyName System.Windows.Forms
2. 正确构造文件列表对象
SetFileDropList方法要求传入System.Collections.Specialized.StringCollection类型的对象,不能直接传单个文件路径。完整的PowerShell执行脚本:
Add-Type -AssemblyName System.Windows.Forms $fileList = New-Object System.Collections.Specialized.StringCollection $fileList.Add("E:\xampp\htdocs\tadiya\webpack.mix.js") | Out-Null [System.Windows.Forms.Clipboard]::SetFileDropList($fileList)
3. Python中调用的正确代码
用subprocess调用时,把完整的PowerShell命令作为参数传递,注意路径转义:
import subprocess ps_command = ''' Add-Type -AssemblyName System.Windows.Forms $fileList = New-Object System.Collections.Specialized.StringCollection $fileList.Add("E:\\xampp\\htdocs\\tadiya\\webpack.mix.js") | Out-Null [System.Windows.Forms.Clipboard]::SetFileDropList($fileList) ''' subprocess.run(["powershell", "-Command", ps_command], check=True)
额外注意点
- 仅Windows系统支持
System.Windows.Forms,PowerShell Core跨平台版在非Windows环境下无法使用该方法。 - 执行脚本的进程需要有桌面交互权限,比如不能在无界面的服务进程中运行,否则无法访问剪贴板。
内容的提问来源于stack exchange,提问作者lava
相关产品推荐
相关产品推荐

