该脚本按预期运行powershell
:
# scripts.py
x = input("type your input: ")
print(f"your input is: {x}")
但是一旦你将它包装成一个模块:
class CSV{
[string] $pythonScript
CSV([string] $pythonPath){
$this.pythonScript = $pythonPath
}
[void] Run(){
python $this.pythonScript
}
}
交互性未打印。要运行此类,请按如下方式创建一个新的 ps1 文件并运行它
# run.ps1
using module .\module.psm1
$newCSV = [CSV]::new(".\script.py")
$newCSV.Run()
在终端中:
PS C:\SE_temp_dir> .\run.ps1
test // typed from user input
PS C:\SE_temp_dir>
请注意,没有打印“输入您的输入”或“您的输入是测试”。我尝试了许多其他方法:
### module.psm1:
python $this.pythonScript | Write-Output
python $this.pythonScript | Write-Host
python -v $this.pythonScript | Write-Host
### script.py:
print(f"your input is: {x}", flush=True)
import sys; sys.stdout.write(f"your input is: {x}")
但它们都不起作用。为什么input()/print()
在普通的 PowerShell 中以交互方式调用 Python 脚本可以正常工作,但在 PowerShell 类的方法中运行时却不行?这是 PowerShell 作用域问题还是主机行为问题?
不确定是否有一种优雅的方法可以在Python 的同一行中为 Python 脚本提供输入,但是,这里有一些针对当前问题的解决方案。在这两种解决方法中,您可能会注意到,
Run
方法的输出类型已从 更改void
为string[]
。第一种方法是我个人使用的,不是在 Python 中请求用户输入,而是在 PowerShell 中执行并将该输入作为参数提供给 Python 脚本:
然后在 Python 中你可以采取第二个
argv
:第二种方法更复杂,不是使用
input
提示,而是使用print
:然后在 PowerShell 中,使用带有逻辑的循环将 Python 脚本输出的第一行直接写入控制台:
根据评论,您的 Python 脚本需要大量用户输入,并且解析它
sys.argv
会是一场噩梦,在这种情况下,您可以使用argparse.ArgumentParser()
多个输入参数来向您的脚本提供:然后在 PowerShell 脚本中您将提供以下参数: