Use python to dynamically create bash aliases

佐手、 提交于 2019-12-11 02:34:17

问题


I'm attempting to use python to dynamically create bash aliases (like, for example, aliases to log in to a set of servers). I'd love to be able to do something like this:

from subprocess import call
SERVERS = [
    ("example", "user@example.com"),
    #more servers in list
]    

for server in SERVERS:
    call('alias %s="ssh %s"' % (server[0], server[1]), shell=True)

The problem is that subprocess launches the jobs in a separate shell session, so the program runs fine, but does nothing to the shell session I run it from.

The same problem occurs with python's os.system or attempting to print the commands and pipe them to bash (all of these create the aliases, but in a new shell that is promptly destroyed after the program finishes).

Ultimately, the goal of this is to run this script from .bashrc

How does one do this?


回答1:


You should write the alias commands to stdout. (eg. just use print).
Then the shell that is calling the Python script can run the alias commands itself.

As commented by @that other guy

eval "$(python yourscript.py)"

in your .bashrc should do it



来源:https://stackoverflow.com/questions/21690811/use-python-to-dynamically-create-bash-aliases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!