検索
ホームページバックエンド開発Python チュートリアルRuby スクリプトからの読み取り時に `readline()` を使用した `subprocess.Popen` がハングするのはなぜですか?これはどうすれば修正できますか?

Why does `subprocess.Popen` with `readline()` hang when reading from a Ruby script, and how can this be fixed?

Python サブプロセス readlines() がハングします

問題:

subprocess.Popen を使用して Ruby スクリプトの出力を読み取るときストリーミング形式で readline() を実行すると、readline() は無期限にハングし、決してハングしません。

背景:

目標は、Ruby ファイルの出力を 1 行ずつストリーミングし、出力全体をバッファリングせずに出力することです。

from subprocess import Popen, PIPE, STDOUT
import pty
import os

file_path = '/Users/luciano/Desktop/ruby_sleep.rb'

command = ' '.join(["ruby", file_path])

master, slave = pty.openpty()
proc = Popen(command, bufsize=0, shell=True, stdout=slave, stderr=slave, close_fds=True)     
stdout = os.fdopen(master, 'r', 0)

while proc.poll() is None:
    data = stdout.readline()
    if data != "":
        print(data)
    else:
        break

print("This is never reached!")

ruby_sleep.rb スクリプトは、2 秒間の単純なメッセージを出力します。遅延:

puts "hello"

sleep 2

puts "goodbye!"

根本原因:

readline() は、Ruby スクリプトが行を終了せずに (つまり、改行なしで) データを出力するため、ハングしたままになります。これにより、readline() は改行が行を完了するまで無期限に待機します。

解決策:

プラットフォームの可用性に応じて、いくつかの解決策が存在します:

  • 向けLinux:

    標準ライブラリの pty を使用して疑似端末 (tty) を開き、Ruby 側で行バッファリングを有効にし、各行が改行で終了するようにします。

    import os
    import pty
    from subprocess import Popen, STDOUT
    
    master_fd, slave_fd = pty.openpty()  # provide tty to enable
                                         # line-buffering on ruby's side
    proc = Popen(['ruby', 'ruby_sleep.rb'],
                 stdin=slave_fd, stdout=slave_fd, stderr=STDOUT, close_fds=True)
    os.close(slave_fd)
    try:
        while 1:
            try:
                data = os.read(master_fd, 512)
            except OSError as e:
                if e.errno != errno.EIO:
                    raise
                break # EIO means EOF on some systems
            else:
                if not data: # EOF
                    break
                print('got ' + repr(data))
    finally:
        os.close(master_fd)
        if proc.poll() is None:
            proc.kill()
        proc.wait()
    print("This is reached!")
  • Linux ベースの場合プラットフォーム:

    標準ライブラリの pty を使用し、マスター ファイル記述子のアクティビティを監視することを選択して、データが非ブロック方式で読み取られるようにします。

    import os
    import pty
    import select
    from subprocess import Popen, STDOUT
    
    master_fd, slave_fd = pty.openpty()  # provide tty to enable
                                         # line-buffering on ruby's side
    proc = Popen(['ruby', 'ruby_sleep.rb'],
                 stdout=slave_fd, stderr=STDOUT, close_fds=True)
    
    timeout = .04 # seconds
    while 1:
        ready, _, _ = select.select([master_fd], [], [], timeout)
        if ready:
            data = os.read(master_fd, 512)
            if not data:
                break
            print("got " + repr(data))
        elif proc.poll() is not None: # select timeout
            assert not select.select([master_fd], [], [], 0)[0] # detect race condition
            break # proc exited
    os.close(slave_fd) # can't do it sooner: it leads to errno.EIO error
    os.close(master_fd)
    proc.wait()
    
    print("This is reached!")
  • クロスプラットフォーム オプション:

    使用stdbuf を使用して、非対話モードで行バッファリングを有効にします。

    from subprocess import Popen, PIPE, STDOUT
    
    proc = Popen(['stdbuf', '-oL', 'ruby', 'ruby_sleep.rb'],
                 bufsize=1, stdout=PIPE, stderr=STDOUT, close_fds=True)
    for line in iter(proc.stdout.readline, b''):
        print line,
    proc.stdout.close()
    proc.wait()

これらのソリューションはすべて、Ruby 側で行バッファリングを有効にし、各行が改行で終了することを保証し、readline( ) 正しく機能します。

以上がRuby スクリプトからの読み取り時に `readline()` を使用した `subprocess.Popen` がハングするのはなぜですか?これはどうすれば修正できますか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Pythonリストをどのようにスライスしますか?Pythonリストをどのようにスライスしますか?May 02, 2025 am 12:14 AM

slicingapythonlistisdoneusingtheyntaxlist [start:stop:step] .hore'showitworks:1)startisthe indexofthefirstelementtoinclude.2)spotisthe indexofthefirmenttoeexclude.3)staptistheincrementbetbetinelements

Numpyアレイで実行できる一般的な操作は何ですか?Numpyアレイで実行できる一般的な操作は何ですか?May 02, 2025 am 12:09 AM

numpyallows forvariousoperationsonarrays:1)basicarithmeticlikeaddition、減算、乗算、および分割; 2)AdvancedperationssuchasmatrixMultiplication;

Pythonを使用したデータ分析では、配列はどのように使用されていますか?Pythonを使用したデータ分析では、配列はどのように使用されていますか?May 02, 2025 am 12:09 AM

Arraysinpython、特にnumpyandpandas、aresentialfordataanalysis、offeringspeedandeficiency.1)numpyarraysenable numpyarraysenable handling forlaredatasents andcomplexoperationslikemoverages.2)Pandasextendsnumpy'scapabivitieswithdataframesfortruc

リストのメモリフットプリントは、Pythonの配列のメモリフットプリントとどのように比較されますか?リストのメモリフットプリントは、Pythonの配列のメモリフットプリントとどのように比較されますか?May 02, 2025 am 12:08 AM

listsandnumpyarraysinpythonhavedifferentmemoryfootprints:listsaremoreflexiblellessmemory-efficient、whileenumpyarraysaraysareoptimizedfornumericaldata.1)listsstorereferencesto objects、with whowedaround64byteson64-bitedatigu

実行可能なPythonスクリプトを展開するとき、環境固有の構成をどのように処理しますか?実行可能なPythonスクリプトを展開するとき、環境固有の構成をどのように処理しますか?May 02, 2025 am 12:07 AM

toensurepythonscriptsbehaveCorrectlyAcrossDevelosment、staging、and Production、usetheseStrategies:1)環境variablesforsimplestetings、2)configurationfilesforcomplexsetups、and3)dynamicloadingforadaptability.eachtododododododofersuniquebentandrequiresca

Pythonアレイをどのようにスライスしますか?Pythonアレイをどのようにスライスしますか?May 01, 2025 am 12:18 AM

Pythonリストスライスの基本的な構文はリストです[start:stop:step]。 1.STARTは最初の要素インデックス、2。ストップは除外された最初の要素インデックスであり、3.ステップは要素間のステップサイズを決定します。スライスは、データを抽出するためだけでなく、リストを変更および反転させるためにも使用されます。

どのような状況で、リストは配列よりもパフォーマンスが向上しますか?どのような状況で、リストは配列よりもパフォーマンスが向上しますか?May 01, 2025 am 12:06 AM

ListSoutPerformArraysIn:1)ダイナミシジョンアンドフレーケンティオン/削除、2)ストーリングヘテロゼンダタ、および3)メモリ効率の装飾、ButmayhaveslightPerformancostsinceNASOPERATIONS。

PythonアレイをPythonリストに変換するにはどうすればよいですか?PythonアレイをPythonリストに変換するにはどうすればよいですか?May 01, 2025 am 12:05 AM

toconvertapythonarraytoalist、usetheList()constructororageneratorexpression.1)importhearraymoduleandcreateanarray.2)useList(arr)または[xforxinarr] toconvertoalistは、largedatatessを変えることを伴うものです。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

SecLists

SecLists

SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。