user1493321
user1493321

Reputation:

Popen.communicate escapes a string I send to stdin

I am trying to spawn a process using Popen and send it a particular string to its stdin.

I have:

pipe = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)
pipe.communicate( my_stdin_str.encode(encoding='ascii') )
pipe.stdin.close()

However, the second line actually escapes the whitespace in my_stdin_str. For example, if I have:

my_stdin_str="This is a string"

The process will see:

This\ is\ a\ string

How can I prevent this behaviour?

Upvotes: 1

Views: 756

Answers (2)

mike
mike

Reputation: 413

Unless you know you need it for some reason, don't run with "shell=True" in general (which, without testing, sounds like what's going on here).

Upvotes: 0

jfs
jfs

Reputation: 414715

I can't reproduce it on Ubuntu:

from subprocess import Popen, PIPE

shell_cmd = "perl -pE's/.\K/-/g'"
p = Popen(shell_cmd, shell=True, stdin=PIPE)
p.communicate("This $PATH is a string".encode('ascii'))

In this case shell=True is unnecessary:

from subprocess import Popen, PIPE

cmd = ["perl", "-pE" , "s/.\K/-/g"]
p = Popen(cmd, stdin=PIPE)
p.communicate("This $PATH is a string".encode('ascii'))

Both produce the same output:

T-h-i-s- -$-P-A-T-H- -i-s- -a- -s-t-r-i-n-g-

Upvotes: 3

Related Questions