2016-06-15 71 views
3

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

在命令行中,我可以创建这个别名: 别名你好=“回声‘世界你好’”

我希望能够运行一个python代替我创建这个别名的脚本。有小费吗?

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

+2

别名是弹不Python或大多数其它编程语言的一个特征来那。他们可能是一个支持噩梦,在我看来,你应该避免除了键盘生产力辅助之外的任何事情。相反,使用函数,这些都是shell函数而不是python函数。 – cdarke

+1

你可以用Python做到这一点,但别名只会在系统命令的生命周期中存在(即不会很长)。 –

+0

如果你使用bash/zsh/..作为你的shell,你可以包含一些东西例如'〜/ .bashrc' /'〜/ .zshrc'中的'alias hello ='echo'hello world'“'等。 Windows Powershell可能有类似的可能性。 –

回答

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

可能希望确保您优雅地处理原始文件缺失其尾随换行符的情况。 –

+0

啊,好点。我想正则表达式是一个更好的方法呢? –

+0

可以用一个换行符预先添加要添加到文件中的内容。:) –

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