【问题标题】:Creating command line alias with python使用 python 创建命令行别名
【发布时间】:2016-10-17 00:10:04
【问题描述】:

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

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

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

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

【问题讨论】:

  • 别名是 shell 的一个特性,而不是 python 的特性,或者大多数其他编程语言都有这个特性。它们可能是支持的噩梦,在我看来,除了键盘生产力辅助之外,您应该避免使用任何其他东西。再次使用函数,这些是 shell 函数而不是 python 函数。
  • 你可以用 Python 做到这一点,但是别名只会在用于创建它的系统命令的生命周期内存在(即不会很长。)
  • 如果你使用 bash/zsh/.. 作为你的 shell,你可以在你的 ~/.bashrc/~/.zshrc 中包含类似 alias hello="echo 'hello world'" 的东西。 Windows Powershell 可能也有类似的可能性。
  • 我可以在 python 脚本中将别名添加到 ~/.bashrc 吗?这个想法是让 python 脚本设置别名供用户将来使用。
  • 只是一个普通的文本文件,只要你细心,编辑是没有问题的。但是在用户启动新的 shell 之前,更改不会生效;仅仅从函数返回是不够的

标签: python bash subprocess alias


【解决方案1】:

您可以这样做,但您必须小心确保别名措辞正确。我假设你在一个类 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()

【讨论】:

  • 可能希望确保您能优雅地处理原始文件缺少尾随换行符的情况。
  • 可以在文件中添加换行符。 :)
  • 啊,我认为通过使用open(file, 'a') 编写它会附加一个换行符。我已经更新了答案
  • 一个符合标准的 UNIX 文本文件应该已经有一个尾随换行符,但有时(当人们使用草率的做法和/或非标准编辑器时)他们没有,在这种情况下,以附加模式打开会赢不会自动修复。编辑后看起来不错。
  • 这行得通! (别名适用于您所说的更改后打开的所有外壳)。谢谢乔纳森!
【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 2016-10-19
    • 2019-09-18
    • 2012-05-30
    相关资源
    最近更新 更多