Python os.getlogin problem

会有一股神秘感。 提交于 2020-01-01 04:12:06

问题


If i create a file like:

import os
print os.getlogin()

and run it with cron, I get an exception

print os.getlogin()
OSError: [Errno 22] Invalid argument

If I run it manually in shell -- it works.

Problem is, GitPython 0.3.1 in commit() uses this function, and i need to use it.

Is there any workaround?

I've tested it on Ubuntu10.10/python2.6.6 and Debian5.0.6/python2.5.2.


回答1:


From the os.getlogin() docs: "Returns the user logged in to the controlling terminal of the process." Your script does not have a controlling terminal when run from cron. The docs go on to suggest: "For most purposes, it is more useful to use the environment variable LOGNAME to find out who the user is, or pwd.getpwuid(os.getuid())[0] to get the login name of the currently effective user id."

Since you don't want to modify GitPython, you could write a script that does this:

import os, pwd

os.getlogin = lambda: pwd.getpwuid(os.getuid())[0]

import git

# do whatever you need to do with GitPython here

I would suggest filing a bug (or better yet, submitting a patch) with GitPython, though.




回答2:


Here is an untested guess about a work-around that might work: os.getlogin() calls getlogin() in the C library, which in turn looks up the login name in the utmp record corresponding to the current process. Since there is no utmp record for cron, you could try to create one using

sessreg -a <logname> ; do_stuff ; sessreg -d <logname>

in your crontab. Maybe you have to twiddle around with the sessreg options. And let me know if this really worked if you tried it :)



来源:https://stackoverflow.com/questions/4399617/python-os-getlogin-problem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!