3

I tried running the following python code in Eclipse on Windows but it is showing errors saying pwd is not a valid import:

import os
import pwd
import socket
pinfo=pwd.getpwuid(os.getuid())

Can I use if not win32 to bypass this part so when it runs on Windows it just jumps at and doesn't create an error?

if not win32:
   import os
   import pwd
   import socket
   pinfo=pwd.getpwuid(os.getuid())
else:
   return

If yes, what do I need to do to use this win32 since it's also showing an error saying undefined variable?

user7116
  • 63,008
  • 17
  • 141
  • 172
Ken Adams
  • 33
  • 2
  • you can (most likely) use a `try`/`except` clause -- or you could rely on `os.name` (`if os.name != 'nt'`) – mgilson Jun 26 '12 at 20:35

4 Answers4

3

You should use sys.platform for that.

if sys.platform != 'win32':
    ...
hmp
  • 941
  • 3
  • 10
  • 27
  • Thank you so much. If you don't mind can you illustrate a little more? like what module I have to import to use this? and will this just run by itself and produce no errors, or is there other things i need to add? Thank you again. – Ken Adams Jun 26 '12 at 21:10
  • You should import the `sys` module first. The problem is that if you want your code to actually do something in Windows, you should supply a Windows version as well :) e.g. `if sys.platform == 'win32': (windows code) else: (unix code)` – hmp Jun 26 '12 at 22:11
  • Thank you for that follow up. One more question if you can be so kind. If it were you, what kind of Windows code would you use to to the same function as that piece of Unix code? Or maybe some direction I can work on, cause I'm lost. Thanks! – Ken Adams Jun 27 '12 at 12:28
  • Look at the links in [Aladdin's response](http://stackoverflow.com/a/11215567/78145) to this question. – hmp Jun 27 '12 at 13:55
2
if sys.platform != 'win32':
 ...
Vader
  • 3,675
  • 23
  • 40
2

I guess those 2 questions may have an answer to your question.

Is there a portable way to get the current username in Python?

What is the Windows equivalent of pwd.getpwnam(username).pw_dir?

Community
  • 1
  • 1
Mahmoud Aladdin
  • 536
  • 1
  • 3
  • 13
1

you can check OS by using

import os
if os.name != 'nt':
   # do something
Maksym Polshcha
  • 18,030
  • 8
  • 52
  • 77