简体   繁体   English

特定目录的PYTHONSTARTUP文件

[英]A PYTHONSTARTUP file for a specific directory

I've heard about the PYTHONSTARTUP file as a way to automatically load specified modules and other code when starting python. 我听说过PYTHONSTARTUP文件是一种在启动python时自动加载指定模块和其他代码的方法。 But PYTHONSTARTUP is a global thing, for all instances of python. 但对于python的所有实例,PYTHONSTARTUP是一个全局的东西。 Is there such a thing as PYTHONSTARTUP that I can place in a specific directory and runs only when I start python in that directory? 有没有PYTHONSTARTUP这样的东西,我可以放在一个特定的目录中,只有当我在该目录中启动python时才运行?

This sounds like you want to use virtualenv . 这听起来像你想使用virtualenv It's a tool for creating isolated python environments with hooks for individual settings. 它是一个用于创建具有用于个别设置的钩子的隔离python环境的工具。 Just put them in the bin/activate of your virtualenv. 只需将它们放入你的virtualenv的bin/activate中。

Just export the PYTHONSTARTUP environment variable before starting up each project. 在启动每个项目之前,只需导出PYTHONSTARTUP环境变量。

export PYTHONSTARTUP=$HOME/myproject/.pystartup
python ~/myproject/start.py

export PYTHONSTARTUP=$HOME/myotherproject/.pystartup
python ~/myotherproject/start.py

Or you could have a simple bash file that contains the environment and the python command you wish to run. 或者你可以有一个简单的bash文件,其中包含你想要运行的环境和python命令。

#!/bin/sh
# filename: workon.sh
export PYTHONSTARTUP=$HOME/myproject/.pystartup
python ~/myproject/start.py

Then: 然后:

./workon.sh

As PYTHONSTARTUP is an environment variable, you can set it on a per-instance basis. 由于PYTHONSTARTUP是一个环境变量,您可以基于每个实例进行设置。

In sh-compatible shells, you can set a variable for the duration of a single process with 在sh兼容的shell中,您可以在单个进程的持续时间内设置变量

PYTHONSTARTUP=/home/you/special.py python arguments ...

To set it permanently for all Python instances, put something like 要为所有Python实例永久设置它,请添加类似的内容

PYTHONSTARTUP=/home/you/regular.py
export PYTHONSTARTUP

in your shell's startup file. 在你的shell的启动文件中。

You can override the global default for the current shell: 您可以覆盖当前shell的全局默认值:

bash$ PYTHONSTARTUP=/home/you/another.py

(and export PYTHONSTARTUP if it's not already exported) or for individual processes as per the first example. (并且如果尚未导出则export PYTHONSTARTUP )或根据第一个示例导出单个进程。

On Windows and in Csh-compatible shells, the details of the syntax will be different, but the concept is by and large the same. 在Windows和兼容Csh的shell中,语法的细节会有所不同,但概念基本相同。

You can add some code in the python startup-file, which only executes depending on your current working directory. 您可以在python启动文件中添加一些代码,该代码仅根据您当前的工作目录执行。

Adding the snippet below in .python prints hello if python is started from /home/myuser/mydir . 如果从/home/myuser/mydir启动python,则在.python添加下面的代码段.python打印hello。

import os

if os.getcwd()=="/home/myuser/mydir":
     print "hello"

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

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