akaur
akaur

Reputation: 415

Backslash ignored while operating a command in python 3

I am trying to run some steps in a software by setting up commands within python as follows :

The commands

cmd="ximage <<EOF\nread image.img\ndetect\\snr=3"
os.system(cmd)

When I execute the last command, it ignored the backslash and gives me the following error :

[XIMAGE> read image.img
Image size = 1000 x 1000 pixels
[XIMAGE> detect\snr=3
 invalid command name "detectsnr=3"

It ignores the backslash while executing the command, although it shows the backslash in the command line. Has anyone seen this issue before ? Any help would be greatly appreciated.

Upvotes: 1

Views: 174

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140168

My advice: eliminate the middleman and make your code more portable by using subprocess & redirection of the input

Moreover, here, the real issue is that you have to use / not \ for your command (reference: ximage manual).

detect/snr_threshold=x
Change the signal to noise acceptance threshold from its default value of 2.

Backslashes are just eliminated from the parsing, no matter how many you're going to put there...

import subprocess
p = subprocess.Popen(["ximage"],stdin=subprocess.PIPE)
out,err = p.communicate(b"read image.img\ndetect/snr=3")
returncode = p.wait()

Like this you can pass the string without risking it being interpreted by the underlying shell (one of the reasons why os.system is deprecated) and it's portable for instance on Windows.

subprocess.communicate takes the input string as argument (of type bytes hence the b prefix)

Upvotes: 3

Related Questions