1

I am trying to use one of the shell commands to a python script, but struggling with some syntax error here.

The description of the command is from here

echo /dev/bus/usb/`udevadm info --name=/dev/ttyUSB0 --attribute-walk | sed -n 's/\s*ATTRS{\(\(devnum\)\|\(busnum\)\)}==\"\([^\"]\+\)\"/\4/p' | head -n 2 | awk '{$1 = sprintf("%03d", $1); print}'` | tr " " "/"

This command works well on the terminal, but trying to import this a python script

import subprocess
cmd = "/dev/bus/usb/`udevadm info --name=/dev/ttyUSB0 --attribute-walk | sed -n 's/\s*ATTRS{\(\(devnum\)\|\(busnum\)\)}==\"\([^\"]\+\)\"/\4/p' | head -n 2 | awk '{$1 = sprintf("%03d", $1); print}'` | tr " " "/""
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, err = p.communicate()
print out
print err

Get a syntax error on a sprintf statement, which doesn't explain much or doesn't like modulo (%)

Vikram
  • 11

1 Answers1

2
  • You can't use " within "'s. Your command split into parts

    cmd = "
    /dev/bus/usb/`udevadm info --name=/dev/ttyUSB0 --attribute-walk 
    | sed -n 's/\s*ATTRS{\(\(devnum\)\|\(busnum\)\)}==\"\([^\"]\+\)\"/\4/p' 
    | head -n 2 
    | awk '{$1 = sprintf("%03d", $1); print}'` 
    | tr " " "/"
    "
    

The " on line 1 and line 7 interfere with the " on lines 5 and 6. You need to escape those. Line 3 escapes them correctly.

See the string literals section.

  • Untested, but you probably need to do it like this:

    cmd = "
    /dev/bus/usb/`udevadm info --name=/dev/ttyUSB0 --attribute-walk 
    | sed -n 's/\s*ATTRS{\(\(devnum\)\|\(busnum\)\)}==\"\([^\"]\+\)\"/\4/p' 
    | head -n 2 
    | awk '{$1 = sprintf(\"%03d\", $1); print}'` 
    | tr \" \" \"/\"
    "
    

Maybe this works too:

cmd = "/dev/bus/usb/`udevadm info --name=/dev/ttyUSB0 --attribute-walk | sed -n 's/\s*ATTRS{\(\(devnum\)\|\(busnum\)\)}==\"\([^\"]\+\)\"/\4/p' | head -n 2 | awk '{$1 = sprintf('%03d', $1); print}'` | tr ' ' '/'"

I changed " into '.

Rinzwind
  • 309,379