Invoking External Scripts Within Running Scripts
Question:
How can you execute a script (e.g., test1.py) that is not defined as a Python module from within a service script (e.g., service.py)?
Answer:
Step 1: Define Functions in the External Script (test1.py)
Create functions within test1.py that encapsulate the desired execution logic. For instance:
def some_func(): print('in test 1, unproductive') if __name__ == '__main__': # test1.py executed as script # do something some_func()
Step 2: Import the External Script into the Service Script (service.py)
In service.py, import the external module using the following code:
import test1
Step 3: Call the Functions from the Service Script
Within the service.py script, call the functions defined in test1.py. For example:
def service_func(): print('service func') if __name__ == '__main__': # service.py executed as script # do something service_func() test1.some_func()
By following these steps, service.py can effectively execute specific functions within test1.py, even though test1.py is not defined as a module.
The above is the detailed content of How Can I Run an External Python Script from Within Another Running Script?. For more information, please follow other related articles on the PHP Chinese website!