How to run .py files created for macros from within a script?

Asked 2 years ago, Updated 2 years ago, 397 views

First of all, suppose you have a file called a.py, which is a simple, unfunctioning description made for macros.
a.py is outside the appropriate location and is not allowed to change.

#a.py C:\tem\a.py
print("a is")
print("executed!")

I would like to call this a.py by condition from b.py.
The flow is

#b.py
i=int(input())

if i == 1:
    Run (a.py)# I want to run a.py outside as described here
else:
    print ("None")

I'd like to do something like that, is it possible?
I would be very grateful if you could give me some advice.

python windows

2022-10-28 10:16

3 Answers

Yes, it's possible.
I think it's different from the original use of import statements, but import a can invoke a.py.
a.py and b.py must be in the same folder.

#b.py
i=int(input())
if i == 1:
    # Run (a.py) # I want to run a.py outside as described here
    import a
else:
    print ("None")

If you are running b.py outside of temp, you must configure additional paths for a.py.

#b.py
i=int(input())

if i == 1:
    # Run (a.py) # I want to run a.py outside as described here
    import sys
    sys.path.append('c:\\temp')
    import a
else:
    print ("None")


2022-10-28 10:16

Here's how it looks like it's running right away.
exec(object[,globals[,locals]])

This function supports the dynamic execution of Python code; the object must be a string or a code object.If it is a string, it is parsed as a series of Python statements and executed (unless there is a syntax error).

Run Python scripts using execfile() method in another Python script

The execfile() function runs the desired file on the interpreter.This function works only with Python 2. Python 3 removed the execfile() function, but Python 3 can do the same with the exec() method.

exec(open("Script1.py").read())

If you write down the relevant part as below, it will be possible.
If necessary, you can specify a dictionary of global and local variables as parameters.

if i==1:
    # I want to run the external a.py as described here
    exec(open(r'C:\tem\a.py', 'r', newline=', encoding='utf8') .read())
else:
    print ("None")


2022-10-28 10:16

From python 3.6, you can now invoke a module in the full path using importlib.util.spec_from_file_location.

sample code

module_name sets any module name, so anything is fine as long as it does not violate the naming convention.
The module name is filepath to a filename (a) with no extension.

from importlib.util import spec_from_file_location, module_from_spec
import pathlib

Def Run (filepath):
    module_name = pathlib.Path(filepath).stem.replace('-', '_')
    spec=spec_from_file_location(module_name, filepath)
    foo=module_from_spec(spec)
    spec.loader.exec_module(foo)

Run (r "C:\tem\a.py")

References


2022-10-28 10:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.