1

I have an existing python script which contains a function ('function_1') and some other lines of code that execute function_1 at some point. Lets call this script 'code_a.py'.

I now have another larger script ('code_b.py'). Within this script, I want code_a.py to run in its entirety.

I'm trying to learn what the best way to do this would be.

Obviously, I could just copy and paste the whole of code_a.py into the body of code_b.py - which seems like a terrible way of doing things.

So I was thinking that at the beginning of code_b.py, I could do something like:

import code_a

But as I understand it, that would only import function_1 from code_a. So should I re-write the whole of code_a as a big function, so that it can be imported into code_b?

Or am I thinking about this is the wrong way?

Thanks.

user1551817
  • 6,693
  • 22
  • 72
  • 109
  • 2
    No, this should import everything in the file. And just a side note, if you ever ask yourself "should I re-write the whole of code_a as a big function", the answer is almost always no. In most cases, the smaller the functions, the better – Carcigenicate Nov 13 '17 at 22:41
  • 2
    If you want to auto-execute something from code_a.py when importing it, you might be able to use an `if __name__ == "code_a":`-like construct. [See here for details and explanation](https://stackoverflow.com/a/419185/8803266) – Oliver Baumann Nov 13 '17 at 22:45
  • Don't knowing about your context and domain, I'd tell you to create a module (or more) with smaller functions implementing the bits of logic needed in code_a and than refactor it to import this module and call it's functions. Than code_b could also call the same functions. It seems like a lot of work but probably will make your life easier in the future, specially if you happen to write code_c which also needs some of those functions. If you write that module you can even use its `__init__.py` to execute some code when it's imported. – Daniel Nov 14 '17 at 00:14

1 Answers1

1

If i understand your problem correctly, you dont want to import function_1 from code_a, you actually want to execute the whole code.

One thing you can do is use the os module in python to execute a shell/cmd command from within code_b.py like so:

import os
os.system('python code_a.py')