English 中文(简体)
后加工线 st
原标题:Subprocess readline gets stuck

我正试图建立一个基于用户投入的终端站。 在产出产生后,我得以拿到产出,但读到正文。 在用户指挥系统执行后,是否可停读。 我增加了一个小的例子,以表明问题:


def communicate_with_subprocess(process, command):
    try:
        # Send the command to the subprocess
        process.stdin.write(command +  
 )
        process.stdin.flush()

        lines = []

        # Read the output from the subprocess
        for _line in iter(process.stdout.readline, b  ):
            if _line ==   :
                break
            lines.append(_line)

        return lines

    except Exception as e:
        print(f"Error executing command  {command} : {e}")
        return None

# Example usage:
subprocess_instance = subprocess.Popen(["/bin/bash"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

try:
    while True:
        user_input = input("Enter a command (type  exit  to quit): ")

        if user_input.lower() ==  exit :
            print("Exiting...")
            break

        output = communicate_with_subprocess(subprocess_instance, user_input)
        print("Output:", output)

finally:
    subprocess_instance.terminate()
    subprocess_instance.wait()

目标是将其纳入Django网络应用,这样,如果存在任何涉及分处理的替代解决办法,这种解决办法也会奏效。

问题回答

缩略语 你想要做的事情是不可能的。

问题在于<代码>处理。 如果在你的分处理中没有任何东西可以读到的话,那就无限期地等待(正如你已经到期)。 通常,这不是一个问题,因为你在你的指挥下关闭了你的分管。 但是,你希望保持开放,因此,你们的读写过程(主要文字/詹戈)如何知道,从你的分处理中没有任何东西可以删除? 也许你会开始一个很长的行动,每10分钟只能产生产出。 因此,机械设备很简单:如果你打电话readline,它最终会等待归还任何物品。

OK...,现在是什么?

你有几种选择:

  • Close your subprocess, after each call (@see communicate) and created every time a new one.
  • You may keep a single open shell process, but you have to communicate in a different way, because of the problem described above.

Last thoughts

我仍然强烈建议考虑另一种做法。 几乎没有任何机会“使”任意用户投入,防止他产生有害的行动/共同点。 除非你信任用户110%,否则你就应考虑严格控制你的指挥,并给予你的用户这一有限选择。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签