本文整理汇总了Python中os.getlogin方法的典型用法代码示例。如果您正苦于以下问题:Python os.getlogin方法的具体用法?Python os.getlogin怎么用?Python os.getlogin使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.getlogin方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: username
# 需要导入模块: import os [as 别名]
# 或者: from os import getlogin [as 别名]
def username(self):
"""
str: Some services require authentication in order to connect to the
service, in which case the appropriate username can be specified. If not
specified at instantiation, your local login name will be used. If `True`
was provided, you will be prompted to type your username at runtime as
necessary. If `False` was provided, then `None` will be returned. You can
specify a different username at runtime using: `duct.username = '<username>'`.
"""
if self._username is True:
if 'username' not in self.__cached_auth:
self.__cached_auth['username'] = input("Enter username for '{}':".format(self.name))
return self.__cached_auth['username']
elif self._username is False:
return None
elif not self._username:
try:
username = os.getlogin()
except OSError:
username = pwd.getpwuid(os.geteuid()).pw_name
return username
return self._username
示例2: __get_user
# 需要导入模块: import os [as 别名]
# 或者: from os import getlogin [as 别名]
def __get_user(self):
if hasattr(os, 'getlogin'):
try:
user = os.getlogin()
if user:
return str(user)
except OSError:
pass
if hasattr(os, 'getuid'):
try:
user = os.getuid()
if user:
return str(user)
except OSError:
pass
user = os.environ.get("USERNAME")
if user:
return str(user)
return None
示例3: test_operadriver_manager_with_selenium
# 需要导入模块: import os [as 别名]
# 或者: from os import getlogin [as 别名]
def test_operadriver_manager_with_selenium():
driver_path = OperaDriverManager().install()
options = webdriver.ChromeOptions()
options.add_argument('allow-elevated-browser')
if get_os_type() in ["win64", "win32"]:
paths = [f for f in glob.glob(f"C:/Users/{os.getlogin()}/AppData/" \
"Local/Programs/Opera/**",
recursive=True)]
for path in paths:
if os.path.isfile(path) and path.endswith("opera.exe"):
options.binary_location = path
elif ((get_os_type() in ["linux64", "linux32"]) and not
os.path.exists('/usr/bin/opera')):
options.binary_location = "/usr/bin/opera"
elif get_os_type() in "mac64":
options.binary_location = "/Applications/Opera.app/Contents/MacOS/Opera"
ff = webdriver.Opera(executable_path=driver_path, options=options)
ff.get("http://automation-remarks.com")
ff.quit()
示例4: extend_app
# 需要导入模块: import os [as 别名]
# 或者: from os import getlogin [as 别名]
def extend_app(app):
"""
Adds the ``--daemon`` argument to the argument object, and sets the
default ``[daemon]`` config section options.
"""
global CEMENT_DAEMON_APP
CEMENT_DAEMON_APP = app
app.args.add_argument('--daemon', dest='daemon',
action='store_true', help='daemonize the process')
# Add default config
user = pwd.getpwnam(os.getlogin())
group = grp.getgrgid(user.pw_gid)
defaults = dict()
defaults['daemon'] = dict()
defaults['daemon']['user'] = user.pw_name
defaults['daemon']['group'] = group.gr_name
defaults['daemon']['pid_file'] = None
defaults['daemon']['dir'] = '/'
defaults['daemon']['umask'] = 0
app.config.merge(defaults, override=False)
app.extend('daemonize', daemonize)
示例5: running_with_sudo
# 需要导入模块: import os [as 别名]
# 或者: from os import getlogin [as 别名]
def running_with_sudo() -> bool:
if verify_running_as_root():
try:
logged_in_user = os.getlogin()
if logged_in_user_is_root(logged_in_user):
return False # when logged in as 'root' user notifications will work.
return True # 'sudo' is used notification won't work.
except FileNotFoundError:
logger.verbose(
"os.getlogin(), returned FileNotFoundError, assuming 'openpyn' is running with 'SUDO'")
return True
except OSError:
logger.verbose(
"os.getlogin(), returned error, assuming 'openpyn' is running with 'SUDO'")
return True
return False # regular user without 'sudo'
示例6: get_file_info
# 需要导入模块: import os [as 别名]
# 或者: from os import getlogin [as 别名]
def get_file_info(self):
"""Internal method to get the file information.
Returns
-------
file_info: dict
dictionary with file information.
"""
# Check if file_info already exists
if hasattr(self, "file_info"):
file_info = self.file_info
else:
file_info = {"date_created": Timestamp.now()}
file_info["date_modified"] = Timestamp.now()
file_info["pastas_version"] = __version__
try:
file_info["owner"] = getlogin()
except:
file_info["owner"] = "Unknown"
return file_info
示例7: send_message
# 需要导入模块: import os [as 别名]
# 或者: from os import getlogin [as 别名]
def send_message(self):
subject = 'Digispark - User: ' + os.getlogin()
text = self.get_text_mail()
msg = MIMEMultipart()
msg['From'] = self.source_mail
msg['To'] = ", ".join(self.dest_mail)
msg['Subject'] = subject
msg.attach(MIMEText(text))
for f in self.files:
attachment = MIMEApplication(open(f, "rb").read(), _subtype="txt")
attachment.add_header('Content-Disposition', 'attachment', filename=f)
msg.attach(attachment)
try:
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.login(self.source_mail, self.source_pass)
mailServer.sendmail(self.source_mail, self.dest_mail, msg.as_string())
mailServer.close()
except:
pass
示例8: get_user_display_name
# 需要导入模块: import os [as 别名]
# 或者: from os import getlogin [as 别名]
def get_user_display_name(interactively_started: bool) -> t.Optional[str]:
"""Gets the display name for the user which started a run
Defaults to MARA_RUN_USER_DISPLAY_NAME and falls back to the current OS-level name
if the run was started interactively, else None.
:param interactively_started: True if the run was triggered interactively
Patch if you have more sophisticated needs.
"""
import os
if 'MARA_RUN_USER_DISPLAY_NAME' in os.environ:
return os.environ.get('MARA_RUN_USER_DISPLAY_NAME')
if not interactively_started:
return None
return os.environ.get('SUDO_USER') or os.environ.get('USER') or os.getlogin()
示例9: get_user_and_home
# 需要导入模块: import os [as 别名]
# 或者: from os import getlogin [as 别名]
def get_user_and_home():
"""Get user name and home directory path
Returns the user account calling the script, *not* 'root' even
when called with 'sudo'.
Returns:
user_name, user_home_dir (tuple): User name and home dir path
Raises:
UserException: If 'getent' command fails
"""
log = logger.getlogger()
user_name = getlogin()
cmd = f'getent passwd {user_name}'
resp, err, rc = sub_proc_exec(cmd, shell=True)
if str(rc) != "0":
msg = 'getent failed:\n{}'.format(err)
log.debug(msg)
raise UserException(msg)
user_home_dir = resp.split(':')[5].rstrip()
return (user_name, user_home_dir)
示例10: get_user_info
# 需要导入模块: import os [as 别名]
# 或者: from os import getlogin [as 别名]
def get_user_info():
"""TODO
Returns
-------
str
``' <username>@<hostname>``
"""
try:
username = os.getlogin()
except (FileNotFoundError, OSError):
username = 'unknown'
if not username:
username = 'unknown'
hostname = socket.gethostname()
if not hostname:
hostname = 'unknown'
return ' ' + username + '@' + hostname
示例11: __init__
# 需要导入模块: import os [as 别名]
# 或者: from os import getlogin [as 别名]
def __init__(self):
self.user = ''
try:
self.user = os.getlogin()
except:
pass
if not self.user:
try:
user = os.environ['USER']
except:
pass
if not self.user:
try:
user = os.environ['LOGNAME']
except:
pass
示例12: get_firefox_db
# 需要导入模块: import os [as 别名]
# 或者: from os import getlogin [as 别名]
def get_firefox_db(db_file):
'''Return the full path of firefox sqlite databases, platform independent'''
success = False
plat_dict = {"Windows 7" : r"C:\Users\%s\AppData\Roaming\Mozilla\Firefox\Profiles" % os.getlogin(),
"Windows XP" : r"C:\Documents and Settings\%s\Application Data\Mozilla\Firefox\Profiles" % os.getlogin(),
"Linux" : r"/home/%s/.mozilla/firefox/" % os.getlogin(),
"Darwin" : r"/Users/%s/Library/Application Support/Firefox/Profiles" % os.getlogin()}
if platform.system() == "Windows":
string = plat_dict[platform.system() + " " + platform.release()]
else:
string = plat_dict[platform.system()]
for item in os.listdir(string):
if os.path.isdir(os.path.join(string, item)) and "default" in item:
if os.path.isfile(os.path.join(string, item, db_file)):
success = True
return os.path.join(string, item, db_file)
if not success:
sys.exit("Couldn't find the database file in the default location! Try providing a different location using the -b option...")
示例13: platform_setting
# 需要导入模块: import os [as 别名]
# 或者: from os import getlogin [as 别名]
def platform_setting():
"""Get OS platform to set folder format
:return: platform work directory
"""
work_dir = None
home_dir = os.environ['HOME'] # get system default setting home folder, for windows
get_login_user = os.getlogin() # get login user name to build user home directory, for linux
# linux
if os.name == 'posix':
if get_login_user != 'root':
work_dir = '/home/' + get_login_user + '/Pictures/Crawler/'
else:
# if your run crawler program in Android Pydroid 3
# change here work_dir to /sdcard/Pictures/Crawler/
work_dir = '/sdcard/Pictures/Crawler/'
# windows
elif os.name == 'nt':
work_dir = home_dir + '/PictureDatabase/Crawler/'
else:
pass
return work_dir
# for filesystem operation entity
示例14: node_power_failure
# 需要导入模块: import os [as 别名]
# 或者: from os import getlogin [as 别名]
def node_power_failure(gyaml, sleep_time=300, name=None):
user = os.getlogin()
if name is None:
name = 'ceph-' + user
driver = get_openstack_driver(gyaml)
for node in driver.list_nodes():
if node.name.startswith(name):
log.info('Doing power-off on %s' % node.name)
driver.ex_stop_node(node)
time.sleep(20)
op = driver.ex_get_node_details(node)
if op.state == 'stopped':
log.info('Node stopped successfully')
time.sleep(sleep_time)
log.info('Doing power-on on %s' % node.name)
driver.ex_start_node(node)
time.sleep(20)
op = driver.ex_get_node_details(node)
if op.state == 'running':
log.info('Node restarted successfully')
time.sleep(20)
return 0
示例15: addToTaskbar
# 需要导入模块: import os [as 别名]
# 或者: from os import getlogin [as 别名]
def addToTaskbar(file_path, dir_path, name):
you = os.getlogin()
startup = os.path.join('C:\\Users', you, 'AppData', 'Roaming',
'Microsoft', 'Internet Explorer', 'Quick Launch',
'User Pinned', 'TaskBar')
name = name + '.lnk'
path = os.path.join(startup, name)
shell = Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = file_path
shortcut.WorkingDirectory = dir_path
shortcut.IconLocation = file_path
shortcut.save()