简体   繁体   中英

Is there a way to 'auto-load' python variables when you create a new script?

I have a set of variables that I am using for many different projects. Is there some sort of config file, or any similar options, that will automatically load a set of pre-defined variables when you make/open a new script?

For example, if I have:

x = "hello"
y = 55

Then I'd like those variables to be automatically defined. I know that the .R profile does something similar in RStudio, but I'm looking for this option in Python. I'm using Spyder IDE, if that helps.

Python does not have any concept of rc files.

If you want to do it in the Python level, you can use the import mechanism to declare the variables in a module and import that on each file that needs.

If you want to do it at the system level, you can create environment variables in your ~/.bashrc for example like:

export PY_X='hello'
export PY_Y=55

Make sure the variables are not overriden later, you can make them more verbose in that case to avoid name clashes.

Then in your Python files, you can can access them from os.environ dict:

x = os.environ.get('PY_X', None)
y = os.environ.get('PY_Y', None)

Otherwise, for having variables only for the python process, you can directly use them at the process start time:

PY_X='hello' PY_Y=55 python ...

Retrieving the env vars are same as mentioned above.

I don't know if this is the best way, but it is a bash script I made a little while back for making new perl files (I changed it to be python for you). Might be helpful depending on how many things you want to put in the file.

#!/bin/bash
# usage
if [ "$1" == "-h" -o -z "$1" ]; then
  echo "Usage: ~/.mkpython file1.py <file2.py>"
  echo "  No  file2.pl passed -> Creates empty file1.py and opens in vim insert mode"
  echo "  Yes file2.pl passed -> Copies file2.py into file1.py and opens vim insert"
  exit 0
fi

# prevents accidental erase of file
if [ -a $1 ]
  then
    read -p "replace file $1? " -n 1 -r
    echo
    if [[ ! $REPLY =~ [Yy]$ ]]
      then
        exit 1
    fi
fi

#copies file 2 into file 1
if [ -n "$2" -a -a $2 ]
  then
    cat $2 > $1
    chmod 0755 $1 && vim $1
    exit 0
fi

#if no file 2 then creates a basic file 1

echo 'Stuff you want in your file goes here' > $1
chmod 0755 $1 && vim -c 'startinsert' $1 +3

This may be of help to you. It describes the IPython configuration system. The long and short of it is that you can put whatever you want in the ~/.ipython/profile_default/ipython_config.py file and it will run every time you fire up the IPython interpreter. If you are using another interpretter then you will have to specify to get a better answer.

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.

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