你可以做到这一点,但你必须小心得到正确的别名措辞。我假设你使用的是类Unix系统,并且正在使用〜/ .bashrc,但类似的代码将可能与其他shell一起使用。
import os
alias = 'alias hello="echo hello world"\n'
homefolder = os.path.expanduser('~')
bashrc = os.path.abspath('%s/.bashrc' % homefolder)
with open(bashrc, 'r') as f:
lines = f.readlines()
if alias not in lines:
out = open(bashrc, 'a')
out.write(alias)
out.close()
,如果你再想别名立即可用,您可能将不得不source ~/.bashrc
之后,然而。我不知道从python脚本执行此操作的简单方法,因为它是bash内建的,并且您无法从子脚本修改现有的父shell,但它可用于您打开的所有后续shell,因为它们会源bashrc。
编辑:
稍微更优雅的解决方案:
import os
import re
alias = 'alias hello="echo hello world"'
pattern = re.compile(alias)
homefolder = os.path.expanduser('~')
bashrc = os.path.abspath('%s/.bashrc' % homefolder)
def appendToBashrc():
with open(bashrc, 'r') as f:
lines = f.readlines()
for line in lines:
if pattern.match(line):
return
out = open(bashrc, 'a')
out.write('\n%s' % alias)
out.close()
if __name__ == "__main__":
appendToBashrc()
别名是弹不Python或大多数其它编程语言的一个特征来那。他们可能是一个支持噩梦,在我看来,你应该避免除了键盘生产力辅助之外的任何事情。相反,使用函数,这些都是shell函数而不是python函数。 – cdarke
你可以用Python做到这一点,但别名只会在系统命令的生命周期中存在(即不会很长)。 –
如果你使用bash/zsh/..作为你的shell,你可以包含一些东西例如'〜/ .bashrc' /'〜/ .zshrc'中的'alias hello ='echo'hello world'“'等。 Windows Powershell可能有类似的可能性。 –