user1551817
user1551817

Reputation: 7471

Incorporating one code into another

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.

Upvotes: 1

Views: 57

Answers (1)

Mohammed Elmahgiubi
Mohammed Elmahgiubi

Reputation: 641

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')

Upvotes: 1

Related Questions