You can do this, but you have to be careful to get the alias wording correct. I'm assuming you're on a Unix-like system and are using ~/.bashrc, but similar code will be possible with other shells.
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()
if you then want the alias to be immediately available, you will likely have to source ~/.bashrc afterwards, however. I don't know an easy way to do this from a python script, since it's a bash builtin and you can't modify the existing parent shell from a child script, but it will be available for all subsequent shells you open since they will source the bashrc.
EDIT:
A slightly more elegant solution:
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()
alias hello="echo 'hello world'"in your~/.bashrc/~/.zshrcor alike. There is probably a similar possibility for the Windows Powershell.