簡體   English   中英

使用python創建命令行別名

[英]Creating command line alias with python

我想在我的python腳本之一中創建命令行別名。 我已經嘗試過os.system(),subprocess.call()(有和沒有shell = True)和subprocess.Popen(),但是我對這些方法都不滿意。 讓您了解我想做什么:

在命令行上,我可以創建以下別名:alias hello =“ echo'hello world'”

我希望能夠運行一個為我創建此別名的python腳本。 有小費嗎?

我也很感興趣然后能夠在python腳本中使用此別名,就像使用subprocess.call(alias)一樣,但這對我來說並不像創建別名那么重要。

您可以執行此操作,但是您必須小心使別名措辭正確。 我假設您使用的是類似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()

這是@Jonathan King'答案的代碼的簡化模擬:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM