【问题标题】:subprocess powershell execution not running after creating exe with pyinstaller使用pyinstaller创建exe后子进程powershell执行未运行
【发布时间】:2021-05-11 14:51:33
【问题描述】:

使用 pyinstaller 创建 .exe 文件后,我的代码出现问题。 我使用Popen() 执行powershell 脚本,但似乎它没有在.exe 版本中执行脚本,而在.py 中它确实有效。

我检查了 stackoverflow 上的其他答案,其中指出您需要重定向所有内容,但这似乎不起作用。

我不确定如何进一步调试或问题的根源是什么。

command = f'powershell.exe; Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass; {path}\config\ps_presto_cli.ps1 -path {path} -usr_pass {usr_pass} -usr_name {usr_name} -sql_code {sql_code} -file_name {file_name}.csv -schema {schema}'

process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout, stderr, stdin = process.communicate()

我用来创建 .exe 文件的命令:

pyinstaller --windowed --noconsole --onefile file.py

有人知道为什么.exe 版本中的Popen() 在上面的示例中不起作用吗?或者我如何进一步调试它(.exe 不会引发错误)。

编辑: 我也试过了:

Popen(['powershell','-command', 'Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass', command], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)

command= f'{path}\config\ps_presto_cli.ps1 -path {path} -usr_pass {usr_pass} -usr_name {usr_name} -sql_code {sql_code} -file_name {file_name}.csv -schema {schema}'

但这也没有用。将'Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass' 移动到 ps1 文件也不起作用。当我这样做时,代码就会挂起。

编辑2: 此主题被标记为重复,但引用的帖子与此处遇到的问题没有任何共同之处。

【问题讨论】:

  • 顺便说一句,这段代码存在注入问题。包含 ; ...some command here...; usr_pass 值可能会导致糟糕的一天。
  • 不过,更大的担忧是powershell.exe; some powershell command here 正在等待powershell.exe 在运行some powershell command here 之前退出;这与让some powershell command here 成为powershell.exe 的输入不同。
  • ...也就是说,这不仅仅是一个pyinstaller的问题;即使没有 pyinstaller,这段代码也不应该永远工作。
  • 鉴于代码确实有效,不确定如何回应。请注意,powershell.exe 命令被发送到 cmd 以打开 powershell。由于我不明白问题是什么,需要如何重写它
  • 链接的副本描述了如何重写它。将要在 powershell 中运行的命令作为参数传递给 powershell,而不是后续命令。

标签: python subprocess pyinstaller


【解决方案1】:

感谢@CharlesDuffy,我找到了问题的答案:

command= f'Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass; {path}\config\ps_presto_cli.ps1 -path {path} -usr_pass {usr_pass} -usr_name {usr_name} -sql_code {sql_code} -file_name {file_name}.csv -schema {schema}'


CREATE_NO_WINDOW = 0x08000000

process = subprocess.Popen(['powershell', command], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, creationflags = CREATE_NO_WINDOW)

现在可执行文件确实可以工作了,唯一剩下的视觉问题是当它执行 ps1 文件时,它会弹出一个终端来执行。

creationflags = CREATE_NO_WINDOW 标志对此有所帮助,尽管我必须为 CREATE_NO_WINDOW 设置变量才能使其工作

【讨论】:

  • 仅针对处理此问题的其他人,creationflags 仅适用于 Window$。
猜你喜欢
  • 1970-01-01
  • 2020-01-23
  • 2017-07-20
  • 2018-10-07
  • 2018-08-16
  • 1970-01-01
  • 2023-04-08
  • 2019-12-25
  • 1970-01-01
相关资源
最近更新 更多