Calling Python Scripts with User Input Using Subprocess
In Python, you may encounter a scenario where you want to execute a script (referred to as "a.py") that prompts the user for input and produces a JSON-formatted output. To automate the execution of this script from another script (named "b.py") using Python's subprocess module, follow these steps:
Import the necessary modules:
<code class="python">import os import sys from subprocess import check_output</code>
Determine the path to the script you want to execute ("a.py"):
<code class="python">script_path = os.path.join(get_script_dir(), 'a.py')</code>
Use the check_output() function to execute "a.py" and provide it with input:
<code class="python">output = check_output([sys.executable, script_path], input='\n'.join(['query 1', 'query 2']), universal_newlines=True)</code>
This command does the following:
By providing input in this manner, you are effectively simulating user interaction with the script. The output can now be used as needed in your "b.py" script.
Additional Alternatives
The above is the detailed content of How to Automate User Input and Retrieve JSON Output from Python Scripts with subprocess?. For more information, please follow other related articles on the PHP Chinese website!