如何在 python 中设置 powershell 的环境



windows powershell terminal中。我可以使用$Env:http_proxy="http://127.0.0.1:7890";$Env:https_proxy="http://127.0.0.1:7890"

但我现在想在windows powershell terminal中执行一个python shell来完成这项工作。我能做这个吗?如何编写python脚本?

从根本上讲,子进程(从PowerShell会话调用的Python脚本总是如此)不能修改其父进程process'环境。

您唯一的选择是:

  • 让Python代码输出用于设置环境变量的指令

  • PowerShell会话必须对其执行操作。

例如:

# Call the Python script (simulated here with a simple command that prints a
# variable-name-value pair) and 
# split the output into variable name and value.
$name, $value = 
(python -c 'print(''http_proxy=http://127.0.0.1:7890'')') -split '=', 2
# Set the environment variable accordingly.
Set-Item "Env:$Name" $value
# Test:
$env:http_proxy # -> 'http://127.0.0.1:7890'

最新更新