使用 python 创建命令行别名

Creating command line alias with python

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

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

我希望能够 运行 一个 python 脚本来为我创建这个别名。有什么建议吗?

我也对能够在 python 脚本中使用此别名感兴趣,例如使用 subprocess.call(别名),但这对我来说不如创建别名是.

你可以这样做,但你必须小心别名的措辞正确。我假设您使用的是类 Unix 系统并且正在使用 ~/.bashrc,但是其他 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 可用,因为它们将提供 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()

这是来自 的代码的简化模拟:

#!/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