मैं मानक इनपुट पढ़ने और स्ट्रीमिंग फैशन में मानक आउटपुट लिखने वाली प्रक्रिया के साथ संवाद करने के लिए पायथन में subprocess
मॉड्यूल का उपयोग करने का प्रयास कर रहा हूं। मैं एक पुनरावर्तक से subprocess पढ़ने लाइनों को चाहते हैं जो इनपुट उत्पन्न करता है, और फिर उपप्रोसेसर से आउटपुट लाइनों को पढ़ता है। इनपुट और आउटपुट लाइनों के बीच एक-से-एक पत्राचार नहीं हो सकता है। मैं एक मनमानी इटरेटर से एक उपप्रोसेसर कैसे खिला सकता हूं जो स्ट्रिंग देता है?मैं पाइथन इटरेटर से उपप्रोसेस के मानक इनपुट को कैसे खिला सकता हूं?
यहाँ कुछ उदाहरण कोड है कि एक साधारण परीक्षण का मामला देता है, और कुछ तरीकों मैंने कोशिश की है कि किसी न किसी कारण के लिए काम नहीं करते:
#!/usr/bin/python
from subprocess import *
# A really big iterator
input_iterator = ("hello %s\n" % x for x in xrange(100000000))
# I thought that stdin could be any iterable, but it actually wants a
# filehandle, so this fails with an error.
subproc = Popen("cat", stdin=input_iterator, stdout=PIPE)
# This works, but it first sends *all* the input at once, then returns
# *all* the output as a string, rather than giving me an iterator over
# the output. This uses up all my memory, because the input is several
# hundred million lines.
subproc = Popen("cat", stdin=PIPE, stdout=PIPE)
output, error = subproc.communicate("".join(input_iterator))
output_lines = output.split("\n")
तो मेरी उपप्रक्रिया एक से पढ़ा कि कैसे मैं कर सकते हैं रेखा से इटरेटर लाइन जब मैं लाइन से अपनी stdout लाइन से पढ़ा?
यदि आप बच्चे की प्रक्रिया में उपयोगकर्ता से बाहर निकलें() ', 'SystemExit' उठाया गया है। इसके बजाय ['os._exit (0)'] (https://docs.python.org/2/library/os.html#os._exit) – hakanc
का उपयोग करना चाहिए [os.fork के बजाय 'थ्रेड() 'का उपयोग करें() '] (http://stackoverflow.com/a/32331150/4279) पोर्टेबिलिटी के लिए और समस्याओं को डीबग करने के लिए विभिन्न कठिन से बचने के लिए। यहां 'os.fork() 'के साथ संभावित मुद्दों का एक उदाहरण दिया गया है: [मानक पुस्तकालय में ताले कांटा पर स्वच्छ होना चाहिए] (http://bugs.python.org/issue6721) – jfs