I want to make a python script(.py) make a UNIX alias that can be accesed after the program has ran. How can i do this?
I have tried this:
#!/usr/bin/python
import os
os.system('alias cdd="cd ~/Desktop/"')
The scope of an alias
command is the shell it is run in. When that shell exits and a new one starts, it will not have the alias defined.
The way persistent customization is provided to shells is with shell scripts that are run when the shell first starts up. For example, bash will run either or both of .bash_profile
and .bashrc
depending on how it is invoked and other local configuration. Refer to the documentation for the shell you're interested in interacting with for all of the specific details of how it handles this.
If you want persistent configuration changes to a shell, you need to modify the shell's startup scripts.
os.system
runs a shell and tells the shell to run the command you supplied. Then the shell exits. So running an alias
command with os.system
can basically accomplish nothing useful.
Here's an example of how you might adjust your bash configuration to define an alias persistently:
with open(expanduser("~/.bashrc"), "at") as bashrc:
bashrc.write(
"\n"
"# Added by myprogram on somedate\n"
"alias cdd='cd ~/Desktop/'\n"
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.