简体   繁体   English

在 Windows shell 到 Python 脚本中设置环境变量

[英]Set Environment Variable in Windows shell through Python Script

To give a little bit of background, I have to set environment variables http_proxy and https_proxy for my school's proxy, and the password changes based on what day it is.为了提供一点背景知识,我必须为我学校的代理设置环境变量http_proxyhttps_proxy ,并且密码会根据当天的日期而变化。 So as a hypothetical example, on Monday the password would be cat, and on Tuesday it would be dog.因此,作为一个假设的例子,星期一的密码是猫,星期二是狗。 The reason way I want to create a Python script to automatically change the password as the day changes is because I have scripts that I run over night, and I do not want to have to go to my computer at 12:01AM and change yesterday's password to today's password.我想创建一个 Python 脚本以在一天的变化时自动更改密码的原因是因为我有一个晚上运行的脚本,我不想在凌晨 12:01 到我的计算机 go 并更改昨天的密码到今天的密码。

I have already written an algorithm for changing my password every day, so that is not the problem or focus of this question.我已经写了一个每天更改密码的算法,所以这不是这个问题的问题或重点。 What I am asking for is a Python script that sets my desired proxy environment variables.我要的是一个 Python 脚本,它设置了我想要的代理环境变量。 I want to be able to type into my terminal SET after I run the Python script and see the http_proxy=... to verify that the environment-variable-setting Python script worked.在运行 Python 脚本并查看http_proxy=...以验证环境变量设置 Python 脚本是否有效后,我希望能够输入我的终端SET I have tried我努力了

import os
os.system['SET http_proxy=user:pass@proxy.edu:port']

and

import os
os.environ["http_proxy"]="user:pass@proxy.edu:port

If you have any further questions, do not hesitate to leave a comment.如果您有任何其他问题,请随时发表评论。

Thank you.谢谢你。

in my case this work fine:在我的例子中,这个工作正常:

os.system(f'setx TOKEN "{env}" /M')

where os.system execute line in cmd and setx setup system env其中 os.system 执行行在 cmd 和 setx 设置系统环境

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM