简体   繁体   English

在python中如何添加到Windows路径变量以查找可执行文件

[英]in python How to add to the windows path variable to find executables

I have been looking for a way to make python search in folders that may not be listed in the windows path. 我一直在寻找一种在Windows路径中未列出的文件夹中进行python搜索的方法。 This way I can account for some non standard locations for installed apps if they decide not to install it under c:\\program files. 这样,如果安装的应用程序决定不将其安装在c:\\ program文件下,则可以为它们确定一些非标准位置。 for instance if unix utils is installed on ad drive or something. 例如,如果unix utils安装在广告驱动器或其他设备上。

Rather than modifying the windows path all the time. 而不是一直修改Windows路径。 I figured I could read the registry find the path it was installed in and then add that to the search path for that python instance and still find what I'm looking for. 我以为我可以阅读注册表来找到它的安装路径,然后将其添加到该python实例的搜索路径中,仍然找到我要查找的内容。 The issue is that I also need to take into account predefined subfolders that have standard naming also. 问题是我还需要考虑具有标准命名的预定义子文件夹。

I have searched and most of what I find is related to modifying the python path and were python finds it modules and this is not really useful for this. 我进行了搜索,发现的大部分内容都与修改python路径有关,并且被python找到了它的模块,而这实际上并没有用。

I have also some across sys.path.append but can't really find anything about whether or not this would work for this. 我在sys.path.append上也有一些,但实际上找不到任何有关此方法是否适用的信息。 I also read the documentation for os.path and it looked like join may work but it didn't really seem to fit for this need. 我还阅读了os.path的文档,看起来join可能起作用,但它似乎并不适合这种需求。

Is there something that I'm just not getting here or is this not possible to do. 是否有我刚到这里的事情,或者这不可能做到?

One last thing it needs to be cross platform compatible. 最后一件事是必须跨平台兼容。 I can find my own paths and add them as needed but just need a way to add to the path. 我可以找到自己的路径并根据需要添加它们,但是只需要一种添加到路径的方法即可。

Thanks 谢谢

To temporarily add to the path, for example: 临时添加到路径,例如:

import os
    import sys

    if sys.platform == 'win32':
        sep = ';'
    else:
        sep = ':'

    os.environ['PATH'] += sep + r'"C:\QA\Hello World"'

Note that on Windows environment variables are not case sensitive, but on UNIX they are. 请注意,在Windows环境变量不区分大小写,但在UNIX环境变量则区分大小写。 This will only add the path for this process, and it's children. 这只会添加此过程的路径,它是子进程。

When you come to run the program, you need to use a shell which will use %PATH% (or $PATH). 当您运行程序时,需要使用将使用%PATH%(或$ PATH)的外壳。

import subprocess
proc = subprocess.Popen('hello.exe',shell=True) 
proc.wait()

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

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