0

This

import pexpect

def run(cmd, stdin):
    child = pexpect.spawn(cmd, encoding='utf-8')
    child.send(stdin)
    child.sendeof()

run('xclip -selection clipboard', 'lol')

should copy string lol into my clipboard, so that I paste it around by Ctrl+v.

But, instead, I get the behaviour of echo -n '' | xclip -selection clipboard i.e. the behaviour of passing empty file as STDIN into xclip.

Why?


UPDATE

This prints lollxl instead of just lxl:

import pexpect

def run(cmd, stdin):
    child = pexpect.spawn(cmd, encoding='utf-8')
    child.send(stdin)
    child.sendeof()
    child.sendeof()
    x = child.read()
    child.wait()
    return x

x = run("sed --expression='s/o/x/g'", 'lol')
print(x)
caveman
  • 422
  • 3
  • 17
  • Is there a reason to use pexpect for this at all, instead of purely standard-library functionality, as in `subprocess.Popen(['xclip', '-selection', 'clipboard'], stdin=subprocess.PIPE, stdout=subprocess.PIPE).communicate('lol')`? – Charles Duffy Aug 21 '20 at 15:07
  • @CharlesDuffy - only reason is to have a single `run` function that works with other commands that require STDIN, STDOUT and TTY piped. If this can be done neatly without pexpect I'll happily leave it and never look back. – caveman Aug 23 '20 at 09:09
  • The only thing of what you listed that `subprocess` doesn't do that `pexpect` does is providing a tty (which frankly is not a very common need). Add `unbuffer` to the beginning of the command line, though, and that'll take care of your tty needs: `subprocess.Popen(['unbuffer', 'xclip', '-selection', 'clipboard'], stdin=subprocess.PIPE, stdout=subprocess.PIPE).communicate('lol')` -- though I don't recommend doing that when you don't _really_ need a tty, and xclip certainly doesn't require one. – Charles Duffy Aug 23 '20 at 12:48
  • Interesting (re: `unbuffer`). Can it be done easily with pure Python using `import pty`? – caveman Aug 23 '20 at 15:20
  • 1
    I don't know -- would need to dig. That actually sounds like a worthwhile Stack Overflow question in and of itself. – Charles Duffy Aug 23 '20 at 16:14

0 Answers0