Home >Backend Development >Python Tutorial >How to Execute an External Python Script from Within Another?
Invoking External Scripts from Running Scripts
In this scenario, we have a standalone Python script, test1.py, and a script called service.py that operates as a service. Our objective is to execute test1.py from within service.py.
To execute an external script, a common approach is as follows:
test1.py
def some_func(): print('in test 1, unproductive') if __name__ == '__main__': # test1.py executed as script # do something some_func()
This script defines a function, some_func(), and when executed directly (as a script), it calls that function.
service.py
import test1 def service_func(): print('service func') if __name__ == '__main__': # service.py executed as script # do something service_func() test1.some_func()
service.py imports test1 and defines its own function, service_func(). In the if name == '__main__' block, it calls both service_func() and test1.some_func(). By importing test1 and directly calling test1.some_func(), service.py can execute the functionality defined in test1.py.
The above is the detailed content of How to Execute an External Python Script from Within Another?. For more information, please follow other related articles on the PHP Chinese website!