Index de l'article

External scripts

Each time you can use def then import your functions (import... __main__...), just do it.

Otherwise, some tips to do in another way.

Import external scripts

Your working script needs to know where to find the external scripts:

sys.path.append('C:\\Users\\Georges\\PycharmProjects\\Your_Directory')
 
from YourScriptWithoutExtension import SomeVariables, ...

But I think all your sub-script will be executed like that.

Include external Python code (without real importation)

Here, at the exec, your sub-script will be executed, and your main script will continue just after.

...
YourFileCode = r'C:/Users/Georges/PycharmProjects/WorkEMC/YourFileCode.py'
...
exec(compile(open(YourFileCode, 'rb').read(), YourFileCode, 'exec'))

Namespace and __main__

If no namespace, so it takes the value __main__, but with an empty namespace, no.

namespace = {}
exec(compile(open(my_script, 'rb').read(), my_script, 'exec'), namespace)

And it is possible to add params or variable in the namespace.

Passing variables from one script to another without interference

Because just importing them, you will execute all scripts when you import.

So just use global variable, in your main script for example:

import os
os.environ['MY_VARIABLE'] = str(my_variable)

Then use it in other scripts like that:

import os
os.environ.get('MY_VARIABLE')

Get the script executing

To know what script is executing another script as an import, in the imported script:

import inspect
 
stack = inspect.stack()
 
print(stack[-1].filename)

 

Liens ou pièces jointes
Télécharger ce fichier (France-Departements-Deformation.zip)France-Departements-Deformation.zip[France-Departements-Deformation]335 Ko
Télécharger ce fichier (simple_countries.zip)simple_countries.zip[simple_countries]1880 Ko