Creating command line alias with python

2024/10/11 20:31:22

I want to create command line aliases in one of my python scripts. I've tried os.system(), subprocess.call() (with and without shell=True), and subprocess.Popen() but I had no luck with any of these methods. To give you an idea of what I want to do:

On the command line I can create this alias: alias hello="echo 'hello world'"

I want to be able to run a python script that creates this alias for me instead. Any tips?

I'd also be interested in then being able to use this alias within the python script, like using subprocess.call(alias), but that is not as important to me as creating the alias is.

Answer

You can do this, but you have to be careful to get the alias wording correct. I'm assuming you're on a Unix-like system and are using ~/.bashrc, but similar code will be possible with other shells.

import osalias = '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()

if you then want the alias to be immediately available, you will likely have to source ~/.bashrc afterwards, however. I don't know an easy way to do this from a python script, since it's a bash builtin and you can't modify the existing parent shell from a child script, but it will be available for all subsequent shells you open since they will source the bashrc.


EDIT:

A slightly more elegant solution:

import os
import realias = '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):returnout = open(bashrc, 'a')out.write('\n%s' % alias)out.close()if __name__ == "__main__":appendToBashrc()
https://en.xdnf.cn/q/69737.html

Related Q&A

Remove unwanted lines in captcha text - opencv - python

I trying to get text from captcha image using opencv. Problem is text are masked with noise and it is complex to process with those horizontal line/noise.Original imageMy processed image :not sure how …

Double Summation in Python

I am trying to write a code to conduct a double summation (see pic) in which; M is the subjects, N is the Trials, Yijt is the measured wave form data (3d array)so far I have; Given Y is the data arra…

psycopg, double and single quotes insert

I ran into problems, while trying to insert to database:ur_psql.execute("""insert into smth(data, filedate, filedby)"""""" values(%s, NOW(), %s)""…

How to debug Python 2.7 code with VS Code?

For work I have to use Python 2.7. But when I use the "debug my python file" function in VS Code, I get an error. Even with a simple program, like : print()

Python Sequence of Numbers

Ive decided not to waste my summer and start learning python. I figured Id start learning looping techniques so I wanted to start with a basic list of numbers, aka, write a for loop that will generate…

Object initializer syntax (c#) in python?

I was wondering if there is a quick way to initialise an object in python. For example in c# you can instantiate an object and set the fields/properties like...SomeClass myObject = new SomeClass() { va…

Plotly.io doesnt see the psutil package even though its installed

Im trying to execute the following code:import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib %matplotlib inline import seaborn as snsimport plotly.graph_objects as g…

How to get MultiCells in Pyfpdf Side by side?

I am making a table of about 10 cells with headings in them. They will not fit accross the page unless I use multi_cell option. However I cant figure out How to get a multi_cell side by side. When I ma…

Django: Require Checkbox to be ticked to Submit Form

Im creating a form in Django (using ModelForm). There are many checkboxes, and I want to make it so that one of these must be selected in order to submit the form. I dont mean any one checkbox, but on…

Filtering in django rest framework

In my project I use django rest framework. To filter the results I use django_filters backend. There is my code:models.pyfrom django.db import modelsclass Region(models.Model):name = models.CharField(m…