Home >Backend Development >Python Tutorial >Here are a few question-based article titles that fit the content: * How to Execute Python Scripts with User Input Using Subprocess? * Capturing Output from Python Scripts: A Guide to Subprocess Tech
Execute Python Scripts with User Input Using Subprocess
When executing a Python script (a.py) from another script (b.py) via subprocess, capturing the script's output can be a challenge. This article provides alternative methods to retrieve the desired output.
Method 1: Passing Input and Capturing Output with Subprocess
<code class="python">import os import sys from subprocess import check_output script_path = os.path.join(get_script_dir(), 'a.py') output = check_output([sys.executable, script_path], input='\n'.join(['query 1', 'query 2']), universal_newlines=True)</code>
Method 2: Importing Modules and Calling Functions
A more flexible approach is to import the target module (a) and call a specific function within it. Ensure a.py uses the if __name__ == "__main__" guard to prevent execution of undesired code upon importing.
<code class="python">import a result = [a.search(query) for query in ['query 1', 'query 2']]</code>
Method 3: Multiprocessing for Parallel Query Execution
If query execution is CPU-intensive, you can utilize multiprocessing to run queries simultaneously:
<code class="python">from multiprocessing import freeze_support, Pool import a if __name__ == "__main__": freeze_support() pool = Pool() # use all available CPUs result = pool.map(a.search, ['query 1', 'query 2'])</code>
The above is the detailed content of Here are a few question-based article titles that fit the content: * How to Execute Python Scripts with User Input Using Subprocess? * Capturing Output from Python Scripts: A Guide to Subprocess Tech. For more information, please follow other related articles on the PHP Chinese website!