ipython: Can I provide input to a shell command

前端 未结 4 1613
广开言路
广开言路 2021-01-18 16:12

Can I execute a shell command that requires input in ipython and/or an ipython notebook?

When I execute such a command, I see it\'s prompt, but no apparent way to p

4条回答
  •  失恋的感觉
    2021-01-18 16:32

    Reposting as an answer, with a bit more detail:

    No, it's a long standing issue that's really difficult to resolve: github.com/ipython/ipython/issues/514

    The issue is roughly that our architecture can't tell when a process is waiting for input, so it doesn't know to prompt the user for input.

    You may be able to use pexpect and raw_input to simulate this for specific programs. I.e. if you say what the prompt looks like, it spots that in the output, and asks the user for input to send back to the process. E.g. for Python:

    import pexpect
    p = pexpect.spawn('python')
    while True:
        try:
            p.expect('\n>>> ')
            print(p.before)
            p.sendline(raw_input('>>> '))
        except pexpect.EOF:
            break
    

    I've just given this a brief test - it works, but it's fairly rough. The concept could be improved.

提交回复
热议问题