2

So I have this uber script which constantly checks the system path for a program (openvpn). When you install openvpn it adds itself to the system path. I run my script in the console and, while it runs and checks, I install openvpn. In that console my script will never find openvpn in sys path. If I open a new console and run the same script it finds it.

Any idea how I can make my script a little less dumb?

import os
import time
import subprocess

def cmd( command ):
    return subprocess.check_output( command, shell = True ) 

def program_in_path( program ):
    path = cmd( "path" ).split(";")
    for p in path:
        if "openvpn" in p.lower():
            return True
    return False


if __name__ == '__main__':
    while True:
        print program_in_path("openvpn")
        time.sleep( 2 )

I presume it's from the shell = True thing but how else would I find it if not with path or WHERE openvpn /Q ? Running with no sehll I get WindowsError: [Error 2] The system cannot find the file specified

Here's slightly the same program done in ruby which works 100%:

loop do
    puts system( "WHERE openvpn /Q" )
    sleep( 5 )
end

Unfortunately my project is too deep into python to switch languages now. Too bad.

4

2 に答える 2

1

おそらく、レジストリから PATH 変数を直接取得するこのアプローチが有効です (Windows を使用しているため)。

たとえば、次のようなことができます。

import winreg

def PathFromReg():
    loc = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
    reg = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
    key = winreg.OpenKey(reg, loc)
    n_val = winreg.QueryInfoKey(key)[1]
    for i in range(n_val):
        val = winreg.EnumValue(key, i)
        if val[0] == 'Path':
                return val[1]

path = PathFromReg()                
print('openvpn' in path.lower())

キーを一度割り当ててから、ループ内で値をクエリするだけでよいと思います。

注: Python 2 では、モジュールは と呼ばれ_winregます。

于 2013-05-17T15:07:48.700 に答える