简体   繁体   English

使用python动态创建bash别名

[英]Use python to dynamically create bash aliases

I'm attempting to use python to dynamically create bash aliases (like, for example, aliases to log in to a set of servers). 我正在尝试使用python动态创建bash别名(例如,登录到一组服务器的别名)。 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. 问题在于,子进程在单独的Shell会话中启动作业,因此程序可以正常运行,但对我从中运行它的Shell会话没有任何作用。

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). python的os.system或尝试打印命令并将其通过管道传送到bash时,也会发生相同的问题(所有这些命令都会创建别名,但在程序完成后会立即销毁的新shell中)。

Ultimately, the goal of this is to run this script from .bashrc 最终,此操作的目标是从.bashrc运行此脚本。

How does one do this? 如何做到这一点?

You should write the alias commands to stdout. 您应该将别名命令写入stdout。 (eg. just use print). (例如,仅使用打印)。
Then the shell that is calling the Python script can run the alias commands itself. 然后,正在调用Python脚本的shell可以运行别名命令本身。

As commented by @that other guy 正如@那个其他人评论的那样

eval "$(python yourscript.py)"

in your .bashrc should do it 在您的.bashrc应该这样做

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM