1

I have several python scripts that all start with the same set of lines, and I would like to be able to change the lines only once.

For example something like this:

import pickle
import sys
sys.path.append("/Users/user/folder/")
import someOtherModules
x=someOtherModules.function()

I know I could save this as a string, and then load the string and run the exec() command, but I was wondering if there is a better way to do this.

In other words, I want to import a list of modules and run some functions at the beginning of every script.

user1763510
  • 1,070
  • 1
  • 15
  • 28

2 Answers2

5

You can define your own module.

# my_init.py
def init():
    print("Initializing...")

And simply add this at the beginning of all your scripts:

import my_init
my_init.init()

Depending on where your scripts and my_init.py are located, you may need to add it to your Python user site directory, see: Where should I put my own python module so that it can be imported

Delgan
  • 18,571
  • 11
  • 90
  • 141
  • If I import modules in the init() function will they also be imported in script after if run my_init.init()? I am trying an example, and not getting it to work. – user1763510 Jan 05 '18 at 18:42
  • in test1.py I have a function def t():import pickle and then in test2.py I import test1 and then run test1.t() but pickle isn't imported into test2. – user1763510 Jan 05 '18 at 18:48
  • @user1763510 No, it will not work. I read your question too quickly, sorry. An alternative would be as proposed by Aiven to do `import a; import b;` in `my_init.py` and then `from my_init import *` in your scripts. But it's not very elegant, the best is to directly import modules into your scripts. – Delgan Jan 05 '18 at 18:48
  • Ok, was just wondering if there was a more elegant/pythonic way to do it. – user1763510 Jan 05 '18 at 18:52
3

You can move all stuff in separate script and in another scripts import everything from it: from my_fancy_script import *. In this case not only code inside my_fancy_script will be executed but also imports will be pushed to another files.

Anyway, better to use Delgan's answer

aiven
  • 3,775
  • 3
  • 27
  • 52