tags:

views:

128

answers:

5

How can I do something like

if sys.argv[0] != '%windir%\\blabla.exe'

I'm having no success at all

A: 

Use os.environ to get the value of the environment variable, and string interpolation to put it with the rest of the string:

execfile = r'%s\blabla.exe' % (os.environ['windir'],)

if sys.argv[0] != execfile:
   ....
Ignacio Vazquez-Abrams
-1 ALWAYS use os.path.join() to assemble paths; it saves you from having to think: oh I'm on Windows so the separator is backslash and oh whoops better put that pesky little `r` at the start of the string constant
John Machin
A: 

You need:

if sys.argv[0] != os.environ.get("windir")

That should do it for you. Just add your blabla.exe on the end of that.

Carl Norum
+2  A: 

This should illustrate how to get the location of Windows:

>>> import os
>>> os.environ['windir']
'C:\\Windows'
nilved
+4  A: 
import os
if sys.argv[0] != os.path.join(os.environ['WINDIR'],'blalah.exe'):
gnibbler
+2  A: 
if sys.argv[0] != '%windir%\\blabla.exe'

What are you trying to do here?

argv[0] is, generally, the filename of the script you are invoking. It would seem unlikely to be blabla.exe, unless you're using some packaging tool to compile yourself into an EXE. If you want to look at the first argument passed to the script, see sys.argv[1].

Also, when you use an %EnvironmentVariable% from the console, the Windows shell will replace the variable name with its content. So when you type myscript.py %windir%\blabla.exe, Windows will replace that with myscript.py C:\Windows\blabla.exe (or similar) before your script gets a look in, and your comparison will fail because the variable name is no longer there.

You can use os.path.expandvars to do the same replacement to your own strings (or just read os.environ yourself). You may also want to absolutize the path so you can compare the real effective path without having to worry about relative paths:

blapath= os.path.expandvars(r'%WinDir%\blabla.exe')
if os.path.abspath(sys.argv[1])==os.path.abspath(blapath):
    ...

In this case, you could also consider os.path.normcase​ing both paths, to allow for Windows's case-insensitivity.

bobince
... unless he's packaging his script as an exe AND putting the result into the %windir% directory (perish the thought). One would hope that his condition always evaluates to False :-) ... otherwise +1 for an answer that addresses all the issues.
John Machin