syscharger
Posts: 19
Joined: Wed Aug 26, 2015 8:46 am

syntax representation (Unterminated quoted string)

Tue Sep 06, 2016 10:20 am

appreciate if some expert can teach me how to represent a sudo command into a python script.

from this (No error)

Code: Select all

sudo iwlist wlan0 scan | grep -i essid | awk -F\" '{ print $2 }' >> essid.txt
to this (ERROR!!)

Code: Select all

os.system(“sudo iwlist wlan0 scan | grep -i essid | awk -F\" '{ print $2 }' >> essid.txt”)
i got this error: Syntax error: Unterminated quoted string

i do not know how to represent the --> \" when calling os.system. Please help.


User avatar
CarlRJ
Posts: 599
Joined: Thu Feb 20, 2014 4:00 am
Location: San Diego, California

Re: syntax representation (Unterminated quoted string)

Tue Sep 06, 2016 7:23 pm

Use your original string, but instead of quoting it with " in front and " at the end, use r''' and '''

The ''' form is called triple quoting, and it takes another ''' to end the quote (much more unlikely to come up in your string than a single ' or "). You can use either single or double quote characters for this (so, ''' or """), they operate the same. The r before the first ''' makes it a raw string, which means that Python won't try to treat the embedded backslash in any special way.

And, if the contents of the file are something you're going to subsequently read into your Python script, there are much better (safer and more efficient) ways to do this:

Code: Select all

#!/usr/bin/env python3

import subprocess
import re

command = ['sudo', 'iwlist', 'wlan0', 'scan']

for line in subprocess.check_output(command).splitlines():
    m = re.match(r'\s*ESSID:"(.*)"', line.decode())
    if m:
        essid = m.group(1)
        print(essid)

FlexibleSigmoid
Posts: 61
Joined: Sun Jul 03, 2016 1:33 am

Re: syntax representation (Unterminated quoted string)

Tue Sep 06, 2016 8:14 pm

Code: Select all

os.system(“sudo iwlist wlan0 scan | grep -i essid | awk -F\" '{ print $2 }' >> essid.txt”)
You only have one double quote. The opening and closing ones aren't proper quotes, they are double backtick quotes.

syscharger
Posts: 19
Joined: Wed Aug 26, 2015 8:46 am

Re: syntax representation (Unterminated quoted string)

Thu Sep 08, 2016 4:22 am

Thanks CarlRJ and hk1963 for your help.
All GOOD !!

Return to “General discussion”