Python调用PowerShell控制显示器定时开关的参数错误求助
解决PowerShell调用SendMessage的语法错误
问题出在你误用了cmd的换行转义符^,PowerShell不识别这个符号,它会被当作C#代码的一部分,引发编译失败。
修正方案1:将^替换为PowerShell换行符`n
直接把代码里的^换成PowerShell的换行转义符`n(注意是反引号),让C#代码的属性和方法分行:
# 开启显示器函数 def turn_monitor_on(): subprocess.run(["powershell", "(Add-Type '[DllImport(\"user32.dll\")]`npublic static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);' -Name a -Pas)::SendMessage(-1,0x0112,0xF170,-1)"]) # 关闭显示器函数 def turn_monitor_off(): subprocess.run(["powershell", "(Add-Type '[DllImport(\"user32.dll\")]`npublic static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);' -Name a -Pas)::SendMessage(-1,0x0112,0xF170,2)"])
修正方案2:写成单行合法C#代码
C#允许属性和方法在同一行(用空格分隔),直接去掉^即可:
# 开启显示器函数 def turn_monitor_on(): subprocess.run(["powershell", "(Add-Type '[DllImport(\"user32.dll\")] public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);' -Name a -Pas)::SendMessage(-1,0x0112,0xF170,-1)"]) # 关闭显示器函数 def turn_monitor_off(): subprocess.run(["powershell", "(Add-Type '[DllImport(\"user32.dll\")] public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);' -Name a -Pas)::SendMessage(-1,0x0112,0xF170,2)"])
额外优化:用Here-String简化PowerShell代码
如果想让C#代码更易读,可以用PowerShell的Here-String来定义多行代码,避免转义麻烦:
import subprocess def turn_monitor_on(): ps_cmd = """(Add-Type @' [DllImport("user32.dll")] public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam); '@ -Name a -Pas)::SendMessage(-1,0x0112,0xF170,-1)""" subprocess.run(["powershell", ps_cmd]) def turn_monitor_off(): ps_cmd = """(Add-Type @' [DllImport("user32.dll")] public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam); '@ -Name a -Pas)::SendMessage(-1,0x0112,0xF170,2)""" subprocess.run(["powershell", ps_cmd])
内容的提问来源于stack exchange,提问作者Murat Sadyrbekov
相关产品推荐
相关产品推荐

