使用python创建命令行别名

时间:2016-06-15 18:15:15

标签: python bash subprocess alias

我想在我的一个python脚本中创建命令行别名。我已经尝试过os.system(),subprocess.call()(有和没有shell = True)和subprocess.Popen(),但我没有运气这些方法。为了让你知道我想做什么:

在命令行上我可以创建这个别名: 别名hello =“echo'hello world'”

我希望能够运行一个为我创建此别名的python脚本。有什么提示吗?

我也有兴趣能够在python脚本中使用这个别名,比如使用subprocess.call(别名),但这对我来说并不像创建别名那样重要。

2 个答案:

答案 0 :(得分:3)

你可以这样做,但你必须小心别名措辞是正确的。我假设您使用的是类似Unix的系统并使用〜/ .bashrc,但其他shell也可以使用类似的代码。

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,因为它们将获取bashrc。

编辑:

稍微优雅的解决方案:

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

答案 1 :(得分:2)

以下是@Jonathan King' answer代码的简化模拟:

#!/usr/bin/env python3
from pathlib import Path  # $ pip install pathlib2 # for Python 2/3

alias_line = 'alias hello="echo hello world"'
bashrc_path = Path.home() / '.bashrc'
bashrc_text = bashrc_path.read_text()
if alias_line not in bashrc_text:
    bashrc_path.write_text('{bashrc_text}\n{alias_line}\n'.format(**vars()))

这是os.path版本:

#!/usr/bin/env python
import os

alias_line = 'alias hello="echo hello world"'
bashrc_path = os.path.expanduser('~/.bashrc')
with open(bashrc_path, 'r+') as file:
    bashrc_text = file.read()
    if alias_line not in bashrc_text:
        file.write('\n{alias_line}\n'.format(**vars()))

我已经尝试过它可以正常工作,但在更改敏感文件时应始终创建备份文件:
$ cp ~/.bashrc .bashrc.hello.backup

相关问题