在该终端内打开终端时执行 python 脚本

Executing a python script when a terminal is opened within that terminal

如果有一种方法可以在您打开终端 window 时 运行 python 脚本,我很感兴趣。例如

print "hello world"

每次打开终端,都会出现hello world。

如果您使用 bash,您在 ~/.bashrc 文件中输入的任何内容在您打开终端时都将是 运行,即

python my_script.py

将执行脚本my_script.py。

Every time i open a terminal, hello world would appear.

就这样:

clrscr("Hello World")                   # or whatever string you want

任何 python 脚本中的任意位置。

要达到这个效果,你必须做以下两件事

1- 为了便于移植,您必须制作一个小模块,如下所示-

# goodManners.py
from os import system as command        # for calling to system's terminal
from platform import system as osName   # for getting the OS's name

def clrscr(text):
    if osName()=='Windows':
        command('cls')
    else:
        command('clear')
    print(text)

2- 现在在你的 ~/.bashrc:

export PYTHONSTARTUP=$HOME/.pythonstartup

并将您的 python 代码放在 $HOME/.pythonstartup 中,例如:

from goodManners import clrscr