如何在 python 中显示用户别名

How to show user aliases in python

我正在尝试在 python 中创建一个脚本来显示我选择的用户的别名,就像您在终端中键入别名时一样。 到目前为止代码是这样的:

tt = open("/etc/passwd" , "r")
 with tt as f2:
    with open("passwd" , "w+") as f1:
        f1.write(f2.read())
        f1.seek(0,0)
        command = f1.read()
        print
        print command

chose = raw_input("select user's name from this list > ")
rootlist = "1) Show user  groups \n2) Show user id \n3) Show users alias\n4) Add new alias \n5) Change Password \n6) Back"
print
print rootlist
print
chose2 = int(raw_input("Choose a command > "))
if choose == 3:
   os.system("alias ")

但是 os.system("alias ") 不起作用,我似乎找不到合适的方法。

别名是一个 shell 内置函数,可以在此处看到

$ type -a alias
alias is a shell builtin

这就是问题所在,您可以通过在 shell 命令中添加对 bash 的调用来解决此问题

import os
os.system('bash -i -c "alias"')

或使用子流程模块的首选方式

from subprocess import Popen, PIPE, STDOUT

cmd = 'bash -i -c "alias"'
event = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
output = event.communicate()[0]
print(output)