1Up
1Up

Reputation: 1044

Launch Python Shell with Predefined Imports and Settings

I am trying to set up a shell-launch script like this:

./practice.py

I intend to debug commands using various modules which can be tedious to import, set up oauth settings, etc.

How do I set example practice.py to launch with this sort of preset:

import module_x
import module_y
from module_z import something

a = something.settings(var_1='123', var_1='456')

>> #start doing stuff

Upvotes: 0

Views: 94

Answers (3)

textshell
textshell

Reputation: 2076

python (and the more comfortable ipython) support -i somefile.py as option to execute the contents of a file before opening the interactive prompt.

on Linux/Unix/OS X you could simply set that as the interpreter of your script like this

#! /usr/bin/python -i
import module_x
# other preloaded settings

On Windows you need to create a batch file or similar to wrap it.

Upvotes: 1

Mehdi
Mehdi

Reputation: 4318

Put a shebang at first line with interactive mode switch:

#!/usr/bin/env python -i

import module_x
import module_y
from module_z import something

a = something.settings(var_1='123', var_1='456')

Then make sure it is executable:

chmod +x practice.py

Then you can run it like this:

./practice.py

Upvotes: 1

Bakuriu
Bakuriu

Reputation: 101919

You can use the PYTHONSTARTUP environmental variable. Quoting the documentation:

PYTHONSTARTUP

If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode. The file is executed in the same namespace where interactive commands are executed so that objects defined or imported in it can be used without qualification in the interactive session. You can also change the prompts sys.ps1 and sys.ps2 and the hook sys.__interactivehook__ in this file.

How you set environmental variables depends on the OS.

Upvotes: 3

Related Questions