使用python创建命令行别名 [英] Creating command line alias with python

查看:142
本文介绍了使用python创建命令行别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的python脚本之一中创建命令行别名。我尝试了os.system(),subprocess.call()(带有和不带有shell = True)和subprocess.Popen(),但是我对这些方法都不满意。为了让您了解我要做什么:

I want to create command line aliases in one of my python scripts. I've tried os.system(), subprocess.call() (with and without shell=True), and subprocess.Popen() but I had no luck with any of these methods. To give you an idea of what I want to do:

在命令行上,我可以创建以下别名:
alias hello = echo'hello world'

On the command line I can create this alias: alias hello="echo 'hello world'"

我希望能够运行一个Python脚本来代替为我创建此别名。还有什么提示吗?

I want to be able to run a python script that creates this alias for me instead. Any tips?

我也很感兴趣然后能够在python脚本中使用此别名,例如使用subprocess.call(alias),但这不是对我来说,创建别名同样重要。

I'd also be interested in then being able to use this alias within the python script, like using subprocess.call(alias), but that is not as important to me as creating the alias is.

推荐答案

您可以执行此操作,但是必须谨慎获取别名措辞正确。我假设您使用的是类似Unix的系统,并且正在使用〜/ .bashrc,但其他shell也可能使用类似的代码。

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()

如果您希望别名立即可用,则可能必须 source〜/ .bashrc 之后。我不知道从python脚本执行此操作的简单方法,因为它是内置的bash,并且您无法从子脚本中修改现有的父shell,但是它将为您随后打开的所有shell提供可用

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.

编辑:

多一点优雅的解决方案:

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()

这篇关于使用python创建命令行别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆