代码来自网络,增加了防止出现中文路径报错的问题。
# -*- coding:utf-8 -*-
def __set_run_as_admin(self):
'设置以管理员身份运行'
if sys.version_info[0] == 3:
ret = ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
else: # in python2.x
cnfile = __file__.decode('gb18030') # 防止__file__路径中有中文
print type(cnfile), cnfile
ret = ctypes.windll.shell32.ShellExecuteW(None, u"runas", unicode(sys.executable), cnfile, None, 1)
if ret > 32:
print 'set run as admin ok ret = %d' %(ret)
#sys.exit(0)
else:
print 'set run as admin fail ret = %d' %(ret)
def __is_run_as_admin(self):
'当前是否以管理员身份运行'
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
# check or set run as admin
if self.__is_run_as_admin():
print 'current is run as admin'
else:
print 'current is not run as admin'
self.__set_run_as_admin()
|