以下是一些適合文章內容並使用問題格式的標題選項: 選項1(聚焦問題): * 如何從使用「subprocess」呼叫的 Python 腳本取得輸出? 奧普蒂奧

DDD
發布: 2024-10-25 21:29:03
原創
490 人瀏覽過

Here are a few title options that fit the article's content and use a question format:

Option 1 (Focus on the problem):

* How Can I Get Output From a Python Script Called Using `subprocess`?

Option 2 (Highlights the solution):

* Retrieving Output fro

使用Subprocess 使用另一個腳本的輸入呼叫Python 腳本

在Python 中,subprocess 模組提供了一個執行外部命令或腳本的方法。但是,當從另一個腳本呼叫 Python 腳本並向其提供輸入時,獲取輸出可能具有挑戰性。

從子程序呼叫取得輸出

擷取輸出在子程序呼叫中,您可以使用 check_output 函數,該函數會擷取外部腳本的標準輸出。以下是實現此目的的方法:

<code class="python">import subprocess

# Path to the external script (a.py)
script_path = 'a.py'

# Input to be provided to the external script
input_data = '\n'.join(['query 1', 'query 2'])

# Execute the external script with input
output = subprocess.check_output([sys.executable, script_path],
                                 input=input_data,
                                 universal_newlines=True)</code>
登入後複製

在此範例中,input_data 是包含 a.py 的輸入查詢的字串。 check_output 函數執行外部腳本,以標準輸入形式提供輸入查詢。傳回的輸出變數現在包含腳本的字串輸出。

替代方法

除了直接使用subprocess 模組之外,還有其他方法可以從內部呼叫Python 腳本腳本:

  • 導入模組: 您可以將外部腳本匯入到主腳本中並直接呼叫其函數。這需要在 a.py 中進行適當的模組級保護。
  • 使用多重處理:如果查詢的計算成本很高,您可以使用多重處理在單獨的進程中執行它們,從而可能提高效能。

以上是以下是一些適合文章內容並使用問題格式的標題選項: 選項1(聚焦問題): * 如何從使用「subprocess」呼叫的 Python 腳本取得輸出? 奧普蒂奧的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!