简体   繁体   English

用python脚本创建一个unix别名

[英]Make a unix alias with python script

I want to make a python script(.py) make a UNIX alias that can be accesed after the program has ran. 我想制作一个python脚本(.py)来创建一个可以在程序运行后加入的UNIX别名。 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. alias命令的范围是它运行的shell。当该shell退出并且新的shell启动时,它将不会定义别名。

The way persistent customization is provided to shells is with shell scripts that are run when the shell first starts up. 向shell提供持久定制的方式是在shell首次启动时运行的shell脚本。 For example, bash will run either or both of .bash_profile and .bashrc depending on how it is invoked and other local configuration. 例如,bash将运行.bash_profile.bashrc一个或两个,具体取决于它的调用方式和其他本地配置。 Refer to the documentation for the shell you're interested in interacting with for all of the specific details of how it handles this. 有关如何处理此问题的所有具体细节,请参阅您有兴趣与之交互的shell的文档。

If you want persistent configuration changes to a shell, you need to modify the shell's startup scripts. 如果要对shell进行持久配置更改,则需要修改shell的启动脚本。

os.system runs a shell and tells the shell to run the command you supplied. os.system运行一个shell并告诉shell运行你提供的命令。 Then the shell exits. 然后shell退出。 So running an alias command with os.system can basically accomplish nothing useful. 因此,使用os.system运行alias命令基本上没有任何用处。

Here's an example of how you might adjust your bash configuration to define an alias persistently: 下面是一个示例,说明如何调整bash配置以持久定义别名:

with open(expanduser("~/.bashrc"), "at") as bashrc:
    bashrc.write(
        "\n"
        "# Added by myprogram on somedate\n"
        "alias cdd='cd ~/Desktop/'\n"
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM