0

I have the following snippet:

#!/usr/bin/env python

import sys

mypath = "D:\inetpub\wwwroot"

if mypath:
        try:
                print "Path: %s" % mypath
                if mypath.find("/"):
                        print "OS: Linux/Unix"
                elif mypath.find(":"):
                        print "OS: Windows"
                else:
                        print "OS: Unknown"
        except:
                print "Error"
else:
        print "[?] OS detection failure."

execution output:

$ python test.py
Path: D:\inetpub\wwwroot
OS: Linux/Unix

What am I doing wrong? I'm getting the opposite result as I expect. Or is there a better way to do this? "/" -> Linux/Unix and ":" -> Windows

bsteo
  • 1,738
  • 6
  • 34
  • 60
  • If you want to detect the OS, why don't you read `sys.platform` directly? If it contains `linux`, then it's Linux. If it contains `win32`, then it's Windows. If it contains `darwin`, then it's Mac OS X. See http://stackoverflow.com/questions/446209/possible-values-from-sys-platform for more. – pts May 11 '13 at 09:06
  • this was just an example, I'm not relying on this to detect OS. – bsteo May 11 '13 at 09:21

3 Answers3

3
#!/usr/bin/env python

import sys

mypath = "D:\\inetpub\\wwwroot"

if mypath:
        try:
                print "Path: %s" % mypath
                if mypath.find("/") >= 0:
                        print "OS: Linux/Unix"
                elif mypath.find(":"):
                        print "OS: Windows"
                else:
                        print "OS: Unknown"
        except:
                print "Error"
else:
        print "[?] OS detection failure."

You need to escape \ otherwise it will assume that the next character has a speacial meaning/binary representation (such as \n´,\t`).

or try:

mypath = r'D:\inetpub\wwwroot'

a better way is to do:

from os.path import abspath
print abspath('D:/inetpub/')

It will automaticly re-work your path to the system specific design, for instance / for linux and \ for Windows :)

or you can do:

import os
if os.name == 'nt':
    print 'Windows'
else:
    print 'Linux/Unix'
Torxed
  • 22,866
  • 14
  • 82
  • 131
  • Python automatically does this (escapes the `'\'`) if the escape sequence is invalid. – Volatility May 11 '13 at 08:46
  • 1
    Yepp but assuming this is stupid/lazy because you will end up with a `\a` or something similar one day and you'll wonder why :) – Torxed May 11 '13 at 08:49
2

The problem is your use of str.find. str.find returns the index of a substring in a string, or -1 otherwise. Because -1 is True in a boolean context, you enter the if block. What you really want is the in operator:

>>> 'hello world'.find('foo')
-1
>>> bool(-1)
True
>>> 'foo' in 'hello world'
False

Your code now should therefore look like this:

#!/usr/bin/env python
import sys

mypath = r'D:\inetpub\wwwroot'  # use a raw string
if mypath:
    try:
        print 'Path:', mypath  # no need for formatting
        if '/' in mypath:
            print 'OS: Linux/Unix'
        elif ':' in mypath:
            print 'OS: Windows'
        else:
            print 'OS: Unknown'
    except:
        print 'Error'
else:
    print '[?] OS detection failure.'

Some suggestions:

  • Use the new str.format method when formatting. It is much more powerful, and is recommended over the old style formatting.
  • You shouldn't have a bare except - it's always a good idea to except specific exceptions, and allows for easy debugging if an unexpected error occurs.
Volatility
  • 31,232
  • 10
  • 80
  • 89
1

You can use in

if "/" in mypath:
    print 'yay :)'

http://docs.python.org/2/library/stdtypes.html#str.find

The find() method should be used only if you need to know the position of sub. To check if sub is a substring or not, use the in operator:

nacholibre
  • 3,874
  • 3
  • 32
  • 35