2

I have a python script that runs on a loop. It will run from a certain user. I only want it to execute the code when a certain user is using the computer. However, if I do switch user, then the python script still runs.

Example:

while 1:
    if user == "kim":
        #do something
        pass



Edit:
The biggest problem with my problem is that the script is still running in my user's account. Even if I switch accounts, my account is still logged in and my account still owns the process. I want to know how to get the currently active user. This is not the same user as the user the Python script is running from. The suggested answers and comments only give me the user from which Python is running from. I am using Yosemite (OS X) and built-in modules are fine, but downloading should be avoided.

Is there a portable way to get the current username in Python? does not solve my problem as it returns the same username even when I switch users.

Community
  • 1
  • 1
jkd
  • 1,045
  • 1
  • 11
  • 27
  • 2
    http://stackoverflow.com/questions/842059/is-there-a-portable-way-to-get-the-current-username-in-python – ForgetfulFellow Feb 09 '15 at 01:42
  • The concept of an (as in single) active user seems straight out of Windows 95. With that said, under Linux, the way I would do it is figure out who was the owner of the X session on Xorg.0 ... if there's a similar process on OS X, you could use subprocess to invoke ps aux | grep [or do it in a much more pythonic way with a 3rd party module, but you specified not wanting to download). Alternatively, you might be able to do widget introspection but I again have no idea if such a thing works outside X (I think there is a similar way in WIndows with related security concerns) – Foon Apr 02 '15 at 23:55

1 Answers1

2

Use the getpasslibrary to get the username.

import getpass

user = getpass.getuser()

while 1:
    if user == "kim":
        #do something
        pass
AlecBrooks
  • 524
  • 4
  • 12
  • @jakekimds I don't have access to an *nix machine at the moment, so I can't replicate the issues that you are having. Have you tried other options from the thread that ForgetfulFellow posted? – AlecBrooks Mar 18 '15 at 22:59
  • Yes I have. I think the trouble is the Python script is not actually running inside the user. It is rather running in the background of my user's account while the other user is active. – jkd Mar 19 '15 at 00:15
  • 1
    Sorry, I think this is rather impossible – jkd Mar 19 '15 at 00:15
  • Yeah, that sounds pretty tricky. I'm sure there would a way to do it, but I wouldn't know where to start. Sorry. – AlecBrooks Mar 19 '15 at 00:25