Home > Backend Development > Python Tutorial > How Can I Run an External Python Script from Within Another Running Script?

How Can I Run an External Python Script from Within Another Running Script?

DDD
Release: 2024-12-21 22:18:14
Original
347 people have browsed it

How Can I Run an External Python Script from Within Another Running Script?

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()
Copy after login

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
Copy after login

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()
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template