[英]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.