简体   繁体   English

如何使用Python将文件夹临时添加到Windows PATH?

[英]How to add a folder to the Windows PATH temporarily with Python?

How can I add multiple folders to the windows PATH in Python on Windows? 如何在Windows上的Python中向Windows PATH添加多个文件夹?

I have multiple programs (wget for windows, phantomjs, casperjs, ...) that I want to use from a python script. 我想从python脚本中使用多个程序(用于Windows,phantomjs,casperjs等的wget)。 And I think it is a good idea to add these folders to the PATH and remove them when the script is ended but I don't know if it's possible... 而且我认为将这些文件夹添加到PATH并在脚本结束时将其删除是个好主意,但我不知道是否有可能...

%PATH% is an environment variable, which is visible in Python by doing this: %PATH%是一个环境变量,可以通过执行以下操作在Python中可见:

import os
print(os.environ['PATH'])

this is a string, which you can make arbitrary modifications to. 这是一个字符串,您可以对其进行任意修改。 So, you might do this: 因此,您可以这样做:

 os.environ['PATH'] += ';C:\\wget'

Any modifications you make will only be visible in your script, and any other processes that you launch from it - you don't need to remove the modifications after you're done just to stop them persisting in the wider OS. 您所做的任何修改将仅在您的脚本以及从该脚本启动的任何其他进程中可见–完成后,您无需删除这些修改只是为了防止它们保留在更广泛的OS中。

import sys

if "C:\\My_Python_Lib" not in sys.path:
    sys.path.append("C:\\My_Python_Lib")

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

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