[Tutor] How to execute python file( python program) by variables from another python program

Alan Gauld alan.gauld at yahoo.co.uk
Wed Oct 7 04:24:33 EDT 2020


On 07/10/2020 07:29, sougoumarane dashnamoorthy wrote:

>    How to execute python file( python program) by variables from another
>    python program

Don't, its nearly always the wrong thing to do!

The best way to execute code in another file is to put the code in a
function then import the file and call the function.
If you don't have control of the file to put the code in a
function then execute it using subprocess, just as you would
a shell script or other executable..

>    I had tried
> 
>    path=__import__('try_main_program_RBModel', globals(), locals(),
>    ['fname'], 0)

There needs to be a very good reason(*) for trying to do this.
It's very easy to get wrong and also easy to break in the future.
And since you know the file you can just use import or one
of its variants - but that brings its own issues(namespace
pollution etc).

(*)One such scenario would be a server process that generates
python code files on the fly and you need to catch these files
and import them into your code - but then you need to know in
advance what that code is going to contain - what variables
and functions it will have etc. There is nearly always a
better solution.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list