使用python动态创建bash别名 [英] Use python to dynamically create bash aliases
问题描述
我试图使用python动态创建bash别名(例如,别名登录到一组服务器)。我很想能够这样做:
从子进程导入调用
SERVERS = [
(example,user@example.com),
#more服务器列表
]
服务器在SERVERS中:
call('别名%s =ssh%s'%(server [0],server [1]),shell = True)
问题是子进程在单独的shell会话中启动作业,所以程序运行正常,但是对于我运行它的shell会话什么也没有。
同样的问题发生在python的 os.system
或尝试打印命令并将其管道到bash(所有这些都创建别名,但在一个新的shell中在程序完成后立即被销毁)。
最终,目标是从.bashrc运行此脚本
如何做到这一点?
您应该将别名命令写入stdout。 (例如,只使用打印)。
然后调用Python脚本的shell可以自己运行别名命令。
由@另一个人
eval$(python yourscript.py)
pre>
在您的
.bashrc
应该这样做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?
解决方案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这篇关于使用python动态创建bash别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!