How execute at least two python files at once when imported?

Cameron Simpson cs at cskk.id.au
Thu Nov 7 02:31:35 EST 2019


On 06Nov2019 08:16, Spencer Du <spencerdu at hotmail.co.uk> wrote:
>Sorry if I haven't stated my requirements clearly.
>I just wanted a way to import at least two python files in parallel and 
>I wanted to know how this can be done or a reason why its bad as stated 
>in another post.

Parallel imports can be fine.

However, you want to avoid parallel code which works on shared data 
structures without the necessary synchronisation may be hazardous.

Your modules look like this:

    import stuff ...

    define functions and classes

    inline code performing a kind of "main programme"

That inline code gets run unconditionally, at import time.

What would be better would be if your modules looked like this:

    import stuff ...

    define functions and classes

    def main():
        inline code performing a kind of "main programme"

Then your "real" main programme can go:

    import your_module1
    import your_module2

    start a thread running your_module1.main()
    start a thread running your_module2.main()

which gets the imports done; they happen in series but just defining 
things (classes and functions) is very fast.

Then dispatch some Threads to run your main functions from each module.

If those main functions do not share data it will probably all just 
work. If they do share data then you may need to debug some 
synchronisation issues; it depends on the code itself.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list