0

I need help converting this bash line to Python 2.6:

# Bash line
ssh -X ${var} users |tr ' ' '\n' |uniq |tr '\n' ' '

The output of this command will go to a variable as a string. So far, this is what I have in Python 2.6:

# Python implementation
string = subprocess.call("ssh -X {0} users |tr \' \' \'\n\' |uniq |tr \'\n\' \' \'".format(var), shell=True)

Is this correct, or is there a better way to do this? Thank you.

  • 1
    You don't need to escape single quotes inside a double-quoted string. – Barmar Jan 08 '20 at 17:52
  • Why do you need `-X`? You're not doing anything that uses X11. – Barmar Jan 08 '20 at 17:55
  • Python 2 is dead now; but even if you can't move to version 3 immediately, certainly at least use 2.7. – tripleee Jan 08 '20 at 18:11
  • ...but you do need to double backslashes in a regular Python string. (In recent Python versions there's a "raw" string type which doesn't require backslashes to be doubled.) – tripleee Jan 08 '20 at 18:13
  • But it would be better to replace the rest of the pipeline with native Python and just call `subprocess.check_output(['ssh', var, 'users'])` in a subprocess, without `shell=True`. – tripleee Jan 08 '20 at 18:16
  • 1
    Also, `subprocess.call()` doesn't return a string at all! But you can switch to `check_output()` if you upgrade to 2.7, or reimplement it using the (clumsy but well documented) `Popen` + `communicate()` sequence. – tripleee Jan 08 '20 at 18:19
  • Maybe see also https://stackoverflow.com/a/51950538/874188 – tripleee Jan 08 '20 at 18:21

0 Answers0