Re: [Tutor] To check for empty string after a portion of the string in python 3.6

2018-12-03 Thread srinivasan
Dear Mr. Cameron

Thanks a lot for your quick responses, Could you please let me know
when the device is not enabled I get the error " I get the below error
saying "IndexError: list index out of range""

Code snippet:
cmd = "sudo hcitool scan"
res = self._helper.execute_cmd_output_string(cmd)
print("The value of res", res)
res = self._helper.execute_cmd_output_string(cmd).split("\n", 2)
print("the value", res)
print("the value", res[1])

if __name__ == "__main__":
m = Bt()
print(m.bluetooth_scan())


1. Output when device is enabled:
The value of res Scanning ...
64:A2:F9:06:63:79 OnePlus 6
the value ['Scanning ...', '\t64:A2:F9:06:63:79\tOnePlus 6']
the value 64:A2:F9:06:63:79 OnePlus 6
None

Process finished with exit code 0

2. Output when device is not enabled

When the device is not connected, I get the below error saying
"IndexError: list index out of range"
The value of res Scanning ...
Traceback (most recent call last):
the value ['Scanning ...']
  File "/home/srinivasan/Downloads/bt_tests/qa/test_library/Bt.py",
line 96, in 
print(m.bluetooth_scan())
  File "/home/srinivasan/Downloads/bt_tests/qa/test_library/Bt.py",
line 74, in bluetooth_scan
print("the value", res[1])
IndexError: list index out of range

Process finished with exit code 1

Could you please do the needful

Thanks in advance



















On Tue, Dec 4, 2018 at 3:09 AM Cameron Simpson  wrote:
>
> Note: post returned to the tutor list.
>
> Please DO NOT cross post to multiple lists (i.e. tutor and python-list,
> as you have). This makes things difficult for people who are not on both
> lists. Pick a _single_ list, and use that.
>
> On 04Dec2018 02:46, srinivasan  wrote:
> >Could you please help me, as am still learning python syntax, how can
> >I add conditional check for empty string after running "hcitool scan"
> >(ie., when there is no Bluetooth devices discovered) ie., after the
> >word  "Scanning..." , when there are no Bluetooth discover-able
> >devices and then return False in the below python code snippet?
> >
> >
> >Command:
> >~$ sudo hcitool scan
> >Scanning ...  -->
> >When there are no BT devices
> >~$ sudo hcitool scan
> >Scanning ...
> >64:A2:F9:06:63:79 OnePlus 6 ---> When there
> >are BT devices
> >~$
> >
> >Python code snippet:
> >def bluetooth_scan(self):
> >"""
> >Start bluetooth scanning process.
> >
> >:return: Return device info by mac address and name.
> >"""
> >cmd = "sudo hciconfig hci0 up"
> >self._helper.execute_cmd_return_code(cmd)
> >
> >cmd = "sudo hcitool scan"
> >res = self._helper.execute_cmd_output_string(cmd)
> >
> >return res
>
> Well you document your function as returning device info by MAC. So part
> the output if "hcitool scan" and for MAC address and name and store that
> in a dictionary (key MAC, value the name). Return the dictionary.
>
> If the dictionary is empty, there were no devices.
>
> Not that like almost all collections, empty dictionaries are "false", so
> you can go:
>
>   bluetooth_devices = scanner.bluetooth_scan()
>   if not bluetooth_devices:
> ... no devices found ...
>
> Cheers,
> Cameron Simpson 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] To check for empty string after a portion of the string in python 3.6

2018-12-03 Thread srinivasan
Dear Python Experts,

Could you please help me, as am still learning python syntax, how can
I add conditional check for empty string after running "hcitool scan"
(ie., when there is no Bluetooth devices discovered) ie., after the
word  "Scanning..." , when there are no Bluetooth discover-able
devices and then return False in the below python code snippet?


Command:
~$ sudo hcitool scan
Scanning ...  -->
When there are no BT devices
~$ sudo hcitool scan
Scanning ...
64:A2:F9:06:63:79 OnePlus 6 ---> When there
are BT devices
~$

Python code snippet:
def bluetooth_scan(self):
"""
Start bluetooth scanning process.

:return: Return device info by mac address and name.
"""
cmd = "sudo hciconfig hci0 up"
self._helper.execute_cmd_return_code(cmd)

cmd = "sudo hcitool scan"
res = self._helper.execute_cmd_output_string(cmd)

return res

Many Thanks in advance,
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error Python version 3.6 does not support this syntax.

2018-11-29 Thread srinivasan
Dear Mats,

Thanks a lot for your quick responses, again the below line seems to
be throwing the same error, is that should I again decode the line
where am facing the issue to str? or could you please let me if there
is any alternative solution for the same or workaround in python 3.6?

Code Snippet:

def parse_device_info(self, info_string):
"""Parse a string corresponding to a device."""
device = {}
block_list = ["[\x1b[0;", "removed"]
string_valid = not any(keyword in info_string for keyword in
block_list) ---> Again this line seems to be
the same issue

if string_valid:
try:
device_position = info_string.index("Device")
except ValueError:
pass
else:
if device_position > -1:
attribute_list = info_string[device_position:].split(" ", 2)
device = {
"mac_address": attribute_list[1],
"name": attribute_list[2]
}

return device

def get_paired_devices(self):
"""Return a list of tuples of paired devices."""
try:
out = self.get_output("paired-devices")
except BluetoothctlError as e:
print(e)
return None
else:
paired_devices = []
for line in out:
device = self.parse_device_info(line)
if device:
paired_devices.append(device)

return paired_devices

if __name__ == "__main__":

print("Init bluetooth...")
bl = Bluetoothctl()
print("Ready!")
bl.start_scan()
print("Scanning for 10 seconds...")
for i in range(0, 10):
print(i)
time.sleep(1)

bl.pair("64:A2:F9:06:63:79")
print("Pairing for 10 seconds...")
for i in range(0, 10):
print(i)
time.sleep(1)

# Seems to be an issue --
bl.get_paired_devices()
print("Getting Paired devices for 10 seconds...")
for i in range(0, 10):
    print(i)
time.sleep(1)

Error Logs:

Traceback (most recent call last):
, in parse_device_info
string_valid = not any(keyword in info_string for keyword in block_list)
  File "/home/srinivasan/Downloads/bt_tests/qa/test_library/bt_tests.py",
line 52, in 
string_valid = not any(keyword in info_string for keyword in block_list)
TypeError: a bytes-like object is required, not 'str'

On Fri, Nov 30, 2018 at 1:18 AM Mats Wichmann  wrote:
>
> On 11/29/18 12:20 PM, srinivasan wrote:
> > Dear Python Experts,
> >
> > With the below code snippet, I am seeing the below error, I am using
> > python 3.6, could you please what could be the issue?
>
> > self.child = pexpect.spawn("bluetoothctl", echo = False)
> ...
> > self.child.send(command + "\n")
> > time.sleep(pause)
> > start_failed = self.child.expect(["bluetooth", pexpect.EOF])
> ...
> > return self.child.before.split("\r\n")
> > --->
> > the issue seems to be here
> > line 27, in get_output
> > return self.child.before.split("\r\n")
> > TypeError: a bytes-like object is required, not 'str'
>
> your types don't match. it's Python 3 so what you get back from talking
> to an external process is a bytes object. you're calling the split
> method on that object, but passing it a string to split on - that's what
> the error is saying.  It shouldn't be any more complicated to fix that
> than to give it a byte object:
>
> return self.child.before.split(b"\r\n")
>
> or... decode the object to a str before splitting on a string.
>
> but since you're specifically splitting on lines, you may as well use
> the splitlines method instead of the split method, since that's what it
> is designed for.
>
>
>
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error Python version 3.6 does not support this syntax.

2018-11-29 Thread srinivasan
Dear Python Experts,

With the below code snippet, I am seeing the below error, I am using
python 3.6, could you please what could be the issue?

Code Snippet:
---
import time
import pexpect
import subprocess
import sys

class BluetoothctlError(Exception):
"""This exception is raised, when bluetoothctl fails to start."""
pass


class Bluetoothctl:
"""A wrapper for bluetoothctl utility."""

def __init__(self):
out = subprocess.check_output("rfkill unblock bluetooth", shell = True)
self.child = pexpect.spawn("bluetoothctl", echo = False)

def get_output(self, command, pause = 0):
"""Run a command in bluetoothctl prompt, return output as a
list of lines."""
self.child.send(command + "\n")
time.sleep(pause)
start_failed = self.child.expect(["bluetooth", pexpect.EOF])

if start_failed:
raise BluetoothctlError("Bluetoothctl failed after running
" + command)

return self.child.before.split("\r\n")
--->
the issue seems to be here

def start_scan(self):
"""Start bluetooth scanning process."""
try:
out = self.get_output("scan on")
except BluetoothctlError as e:
print(e)
return None

if __name__ == "__main__":

print("Init bluetooth...")
bl = Bluetoothctl()
print("Ready!")
    bl.start_scan()
print("Scanning for 10 seconds...")
for i in range(0, 10):
print(i)
time.sleep(1)

Error Logs:
-
/home/srinivasan/Downloads/bt_tests/qa/venv/bin/python
/home/srinivasan/Downloads/bt_tests/qa/test_library/bt_tests.py
Init bluetooth...
Ready!
Traceback (most recent call last):
  File "/home/srinivasan/Downloads/bt_tests/qa/test_library/bt_tests.py",
line 169, in 
bl.start_scan()
  File "/home/srinivasan/Downloads/bt_tests/qa/test_library/bt_tests.py",
line 32, in start_scan
out = self.get_output("scan on")
  File "/home/srinivasan/Downloads/bt_tests/qa/test_library/bt_tests.py",
line 27, in get_output
return self.child.before.split("\r\n")
TypeError: a bytes-like object is required, not 'str'

Process finished with exit code 1

On Wed, Nov 28, 2018 at 12:17 AM Mats Wichmann  wrote:
>
> On 11/27/18 5:50 AM, srinivasan wrote:
> > Dear Python Experts,
> >
> > As still I am newbie and learning python, I am trying to reuse the
> > Bluetoothctl wrapper in Python from the link (
> > https://gist.github.com/egorf/66d88056a9d703928f93) I am using python3.6
> > version, In pycharm editor on the bold highlighted code snippets I see the
> > error message "Python version 3.6 does not support this syntax.",
>
> once again you've posted in a way that inserts lots of extra crud, you
> avoided that last time.
>
> The syntax change is simple (and works on most older Pythons too):
>
> except ErrorType, e:
>
> becomes
>
> except ErrorType as e:
>
>
> >
> > Could you please how help me how the below highlighted lines of code can be
> > can be ported to python3.6 version?
> >
> > *except BluetoothctlError, e:*
> >
> > *print(e)*
> > *return None*
> >
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Error Python version 3.6 does not support this syntax.

2018-11-27 Thread srinivasan
Dear Python Experts,

As still I am newbie and learning python, I am trying to reuse the
Bluetoothctl wrapper in Python from the link (
https://gist.github.com/egorf/66d88056a9d703928f93) I am using python3.6
version, In pycharm editor on the bold highlighted code snippets I see the
error message "Python version 3.6 does not support this syntax.",

Could you please how help me how the below highlighted lines of code can be
can be ported to python3.6 version?

*except BluetoothctlError, e:*

*print(e)*
*return None*

Full Code snippet:
==

import time
import pexpect
import subprocess
import sys

class BluetoothctlError(Exception):
"""This exception is raised, when bluetoothctl fails to start."""
pass

class Bluetoothctl:
"""A wrapper for bluetoothctl utility."""

def __init__(self):
out = subprocess.check_output("rfkill unblock bluetooth", shell =
True)
self.child = pexpect.spawn("bluetoothctl", echo = False)

def get_output(self, command, pause = 0):
"""Run a command in bluetoothctl prompt, return output as a list of
lines."""
self.child.send(command + "\n")
time.sleep(pause)
start_failed = self.child.expect(["bluetooth", pexpect.EOF])

if start_failed:
raise BluetoothctlError("Bluetoothctl failed after running " +
command)

return self.child.before.split("\r\n")

def start_scan(self):
"""Start bluetooth scanning process."""
try:
out = self.get_output("scan on")


*except BluetoothctlError, e:print(e)return
None*

def make_discoverable(self):
"""Make device discoverable."""
try:
out = self.get_output("discoverable on")



*   except BluetoothctlError, e:print(e)return
None*
def parse_device_info(self, info_string):
"""Parse a string corresponding to a device."""
device = {}
block_list = ["[\x1b[0;", "removed"]
string_valid = not any(keyword in info_string for keyword in
block_list)

if string_valid:
try:
device_position = info_string.index("Device")
except ValueError:
pass
else:
if device_position > -1:
attribute_list = info_string[device_position:].split("
", 2)
device = {
"mac_address": attribute_list[1],
"name": attribute_list[2]
}

return device

def get_available_devices(self):
"""Return a list of tuples of paired and discoverable devices."""
try:
out = self.get_output("devices")


*except BluetoothctlError, e:print(e)return
None*
else:
available_devices = []
for line in out:
device = self.parse_device_info(line)
if device:
available_devices.append(device)

return available_devices

def get_paired_devices(self):
"""Return a list of tuples of paired devices."""
try:
out = self.get_output("paired-devices")


*except BluetoothctlError, e:print(e)return
None*
else:
paired_devices = []
for line in out:
device = self.parse_device_info(line)
if device:
paired_devices.append(device)

return paired_devices

def get_discoverable_devices(self):
"""Filter paired devices out of available."""
available = self.get_available_devices()
paired = self.get_paired_devices()

return [d for d in available if d not in paired]

def get_device_info(self, mac_address):
"""Get device info by mac address."""
try:
out = self.get_output("info " + mac_address)


*except BluetoothctlError, e:print(e)return
None*
else:
return out

def pair(self, mac_address):
"""Try to pair with a device by mac address."""
try:
out = self.get_output("pair " + mac_address, 4)


*except BluetoothctlError, e:print(e)return
None*
else:
res = self.child.expect(["Failed to pair", "Pairing
successful", pexpect.EOF])
success = True if res == 1 else False
return success

def remove(self, mac_address):
"""Remove paired device by mac address, return success of the
operation."""
try:
out = self.get_output("remove " + mac_address, 3)


*except BluetoothctlError, e:print(e)return
None*
else:
res = self.child.expect(["not available", "Device has been
removed", pexpect.EOF])
success = True if res == 1 else False
return succes

Re: [Tutor] Issue in using "subprocess.Popen" for parsing the command output

2018-11-27 Thread srinivasan
Dear All,

I have fixed  the issue with below code snippet for parsing the
command output without try and exception, pls let me know if any
improvements are needed, might be useful for others


def to_bytes(self, str):
# Encode to UTF-8 to get binary data.
if isinstance(str, bytes):
return str
return str.encode('utf-8')

def to_string(self, bytes):
if isinstance(bytes, str):
return bytes
return self.to_bytes(bytes)

def convert_string(self, bytes):
try:
return self.to_string(bytes.decode('utf-8'))
except AttributeError:  # 'str' object has no attribute 'decode'.
return str(bytes)
except UnicodeError:
return str(bytes)

def sample(self, ssid, pw):

cmd = "nmcli device wifi connect '%s' password '%s'" % (ssid, pw)

p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
 shell=True)
out, err = p.communicate()
out = self.convert_string(out)
err = self.convert_string(err)

print("The value of data", out.split(" "))

print("printing stdout!!", out)

print("printing err!!", err)

print("printing retcode!!", p.returncode)

if p.returncode != 0:
raise subprocess.CalledProcessError(cmd=cmd,
returncode=p.returncode,

output="{}\n{}".format(out, err))

return out

if __name__ == "__main__":
m = bt()

print(m.sample("NIassddWiFi", "T.f.o.s.1996!abcdfg"))
On Sun, Nov 25, 2018 at 11:05 PM Steven D'Aprano  wrote:
>
> I think you are sending email using Gmail. If so, there is a command in
> Gmail to send only PLAIN TEXT with no added formatting. Please use it.
> Your code at the moment has extra asterisks * added at the beginning and
> end of each line.
>
> More comments below.
>
>
> On Sun, Nov 25, 2018 at 10:43:10PM +0530, srinivasan wrote:
>
> > 1. Am trying to improve the below code with "try" and "exception", could
> > you please help me how "try" and "exception" can be used on the below code
> > snippet. I hope in my code with try and exception, seems to be a bug.
>
> As a beginner, you should normally not use try...except to report
> errors. You should learn how to diagnose errors by reading the
> traceback. Covering up the traceback with try...except makes debugging
> harder.
>
> Your use here:
>
>
> > *try:*
> > *cmd = "nmcli device wifi connect '%s' password '%s'" % (ssid, pw)*
> > *proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, 
> > stderr=subprocess.PIPE, shell=True, universal_newlines=True)*
> > *stdout, stderr = proc.communicate()*
> > *retcode = proc.returncode*
> > *print("printing stdout!!", stdout)*
> > *print("printing retcode!!", retcode)*
> > *except subprocess.CalledProcessError as e:*
> > *s = """While executing '{}' something went wrong.*
> > *Return code == '{}'*
> > *Return output:\n'{}'*
> > *""".format(cmd, e.returncode, e.output, 
> > shell=enable_shell)*
> > *raise AssertionError(s)*
>
> doesn't seem right to me. The string.format() method doesn't take a
> shell=enable_shell agument, so I expect that line
>
> s = """...""".format(cmd, ..., shell=enable_shell)
>
> to fail. But even if it doesn't fail, the next line:
>
> raise AssertionError(s)
>
> is an abuse of exceptions. The failure here is *not* an assertion, and
> you shouldn't use AssertionError. You wouldn't use TypeError or
> UnicodeEncodeError or AttributeError. "AssertionError" should not be
> used for "some arbitrary error".
>
> There are almost no reasons to manually raise AssertionError, except
> perhaps in test frameworks like unittest. Normally you should only get
> an AssertionError from the "assert" command:
>
> https://import-that.dreamwidth.org/676.html
>
> My opinion is, you should remove that try...except altogether. I don't
> think that it helps your code, even if it worked. Calls to Popen can
> fail in many, many ways, and it seems pointless to single out just one
> of them and to replace th

Re: [Tutor] Issue in using "subprocess.Popen" for parsing the command output

2018-11-25 Thread srinivasan
Even only with "*proc.decode("utf-8")"* in the above code still it seems to
throw the error

#return proc.strip().decode("utf-8")
#return proc.decode("utf-8").strip()
*return proc.decode("utf-8")*

Error:
/home/srinivasan/Downloads/wifidisconnectissuenov23_homework/venv/bin/python
/home/srinivasan/Downloads/wifidisconnectissuenov23_homework/qa/test_library/test4.py
printing stdout!!
printing retcode!! 0
Traceback (most recent call last):
  File
"/home/srinivasan/Downloads/wifidisconnectissuenov23_homework/qa/test_library/test4.py",
line 31, in 
main("Apartment 18", "40672958689850014685")
*  File
"/home/srinivasan/Downloads/wifidisconnectissuenov23_homework/qa/test_library/test4.py",
line 29, in main*
*return proc.decode("utf-8")*
*AttributeError: 'Popen' object has no attribute 'decode'*

Process finished with exit code 1


On Sun, Nov 25, 2018 at 11:24 PM srinivasan 
wrote:

> Hope now I have changed on the string output as below, could you please
> correct me if am still wrong?
>
> import sys
> import subprocess
>
> interface = "wlan0"
>
>
> def main(ssid, pw):
>
> try:
> cmd = "nmcli device wifi connect '%s' password '%s'" % (ssid, pw)
>
> proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
> stderr=subprocess.PIPE, shell=True, universal_newlines=True)
> stdout, stderr = proc.communicate()
> retcode = proc.returncode
>
> print("printing stdout!!", stdout)
> print("printing retcode!!", retcode)
>
> except subprocess.CalledProcessError as e:
> s = """While executing '{}' something went wrong.
> Return code == '{}'
> Return output:\n'{}'
> """.format(cmd, e.returncode, e.output, shell=True)
> raise AssertionError(s)
>
> #return proc.strip().decode("utf-8")
> *return proc.decode("utf-8").strip()*
>
> main("Apartment 18", "40672958689850014685ad")
>
> Error:
>
> /home/srinivasan/Downloads/wifidisconnectissuenov23_homework/venv/bin/python
> /home/srinivasan/Downloads/wifidisconnectissuenov23_homework/qa/test_library/test4.py
> Traceback (most recent call last):
>   File
> "/home/srinivasan/Downloads/wifidisconnectissuenov23_homework/qa/test_library/test4.py",
> line 30, in 
> main("Apartment 18", "40672958689850014685")
> *  File
> "/home/srinivasan/Downloads/wifidisconnectissuenov23_homework/qa/test_library/test4.py",
> line 28, in main*
> *return proc.decode("utf-8").strip()*
> *AttributeError: 'Popen' object has no attribute 'decode'*
> printing stdout!!
> printing retcode!! 0
>
> Process finished with exit code 1
>
>
>
> On Sun, Nov 25, 2018 at 11:19 PM MRAB  wrote:
>
>> On 2018-11-25 17:13, srinivasan wrote:
>> > Dear Python Experts Team,
>> >
>> > As am newbie still learning the python syntax from past 2 weeks, Excuse
>> me,
>> > If this might be silly question, As I am trying to execute shell command
>> > (ie, nmcli) using "subprocess.Popen".
>> >
>> > 1. Am trying to improve the below code with "try" and "exception", could
>> > you please help me how "try" and "exception" can be used on the below
>> code
>> > snippet. I hope in my code with try and exception, seems to be a bug.
>> >
>> > 2. As I am trying to execute shell commands using "subprocess.Popen", I
>> am
>> > trying to parse the strings output by "cmd = "nmcli device wifi connect
>> > '%s' password '%s'" % (ssid, pw)" command as below, but it is throwing
>> the
>> > below error as shown in "Output error logs:"
>> >
>> >   Could you please let me to fix the bug in the below code snippet,
>> where I
>> > need the collect the strings of the command output and later how to be
>> > parsed after execution of the command for example, I need to parse the
>> > string "Connection activation failed: " and compare it with the command
>> > output, could you please help me how this can be achieved?
>> >
>> > *Command:*
>> > :~$ nmcli device wifi connect 'Apartment 18' password
>> > '40672958689850014685abcdf'
>>

[Tutor] Issue in using "subprocess.Popen" for parsing the command output

2018-11-25 Thread srinivasan
Dear Python Experts Team,

As am newbie still learning the python syntax from past 2 weeks, Excuse me,
If this might be silly question, As I am trying to execute shell command
(ie, nmcli) using "subprocess.Popen".

1. Am trying to improve the below code with "try" and "exception", could
you please help me how "try" and "exception" can be used on the below code
snippet. I hope in my code with try and exception, seems to be a bug.

2. As I am trying to execute shell commands using "subprocess.Popen", I am
trying to parse the strings output by "cmd = "nmcli device wifi connect
'%s' password '%s'" % (ssid, pw)" command as below, but it is throwing the
below error as shown in "Output error logs:"

 Could you please let me to fix the bug in the below code snippet, where I
need the collect the strings of the command output and later how to be
parsed after execution of the command for example, I need to parse the
string "Connection activation failed: " and compare it with the command
output, could you please help me how this can be achieved?

*Command:*
:~$ nmcli device wifi connect 'Apartment 18' password
'40672958689850014685abcdf'
Error: Connection activation failed: (7) Secrets were required, but not
provided.
:~$

*Code:*
*import sys*
*import subprocess*

*interface = "wlan0"*


*def main(ssid, pw):*

*# cmd = "nmcli device wifi connect '%s' password '%s'" % (ssid, pw)*
*#*
*# proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=True,  universal_newlines=True)*
*# stdout, stderr = proc.communicate()*
*# retcode = proc.returncode*
*#*
*# print("printing stdout!!", stdout)*
*# print("printing retcode!!", retcode)*

*try:*
*cmd = "nmcli device wifi connect '%s' password '%s'" % (ssid, pw)*

*proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=True, universal_newlines=True)*
*stdout, stderr = proc.communicate()*
*retcode = proc.returncode*

*print("printing stdout!!", stdout)*
*print("printing retcode!!", retcode)*

*except subprocess.CalledProcessError as e:*
*s = """While executing '{}' something went wrong.*
*Return code == '{}'*
*    Return output:\n'{}'*
*    """.format(cmd, e.returncode, e.output,
shell=enable_shell)*
*raise AssertionError(s)*

*return proc.strip().decode("utf-8")*

*main("Apartment 18", "40672958689850014685")*

*Output error logs:*

/home/srinivasan/Downloads/wifidisconnectissuenov23/qa/venv/bin/python
/home/srinivasan/Downloads/wifidisconnectissuenov23/qa/test_library/test4.py
Traceback (most recent call last):
  File
"/home/srinivasan/Downloads/wifidisconnectissuenov23/qa/test_library/test4.py",
line 38, in 
printing stdout!!
printing retcode!! 0
main("Apartment 18", "40672958689850014685")
  File
"/home/srinivasan/Downloads/wifidisconnectissuenov23/qa/test_library/test4.py",
line 36, in main
return proc.strip().decode("utf-8")
AttributeError: 'Popen' object has no attribute 'strip'

Process finished with exit code 1

Kindly do the needful as am stuck with this issue from 2 days

Many Thanks in advance,
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Issue in parsing the string output from the command using "subprocess"

2018-11-18 Thread srinivasan
Dear Python Experts Team,

As am newbie to python and learning python, working on embedded linux
platform, my intention is to delete all the SSID's before connecting my
Wi-Fi module to specific SSID., I am trying to parse command output using
the "subprocess"  with wrapper "execute_cmd_output_string" written on
it described
as below,  using the nmcli commands "*nmcli -t -f TYPE,UUID con" and "**"nmcli
connection delete uuid ".*

Could you please help me, what could be the bug in the below method "*def
wifi_disconnect_reconnect(self, ssid, pw):"  *using the method
"execute_cmd_output_string" (in-turn uses "subprocess") which is failing to
give correct output of., UUID's  for *"nmcli connection delete uuid "*  ?

But which works fine with "commands.getstatusoutput" (res =
commands.getstatusoutput("nmcli -t -f TYPE,UUID con")), but I dont want to
include "commands.getstatusoutput" which costs me for including one more
python module in my rootfs

Typical output for "nmcli -t -f TYPE,UUID con"

~$ nmcli -t -f TYPE,UUID con
802-11-wireless:3f5011d4-5681-4fed-8dea-95dee790e9e2
802-11-wireless:bfb93be0-740d-426e-b215-0fdc2f652877
802-11-wireless:69b60cf4-65aa-442b-a54c-fb82905adb0d
802-11-wireless:dc2a15ec-d3da-491e-9c8f-cb054f375837
802-11-wireless:5164e7f2-4489-462e-b093-76bc51bf1303
802-11-wireless:d462e8c4-fac7-42f2-8f9a-6846f52d4e8c
802-11-wireless:e5020744-5c9c-453c-92ec-7a854fc893e6
802-11-wireless:eed3358e-8635-471d-b7e9-5c2973a05128
802-11-wireless:ceea6707-a929-4941-9047-a75e061914b6
802-11-wireless:dd6b9c83-db7b-42b9-99c0-14a04f6f35f5
802-11-wireless:9f764fff-6288-49c4-9412-902e89230136
802-11-wireless:72c627cd-77a3-4d16-bb2c-058040d8e4fc
~$

*Python Code Snipeet:*
*--*
*def wifi_disconnect_reconnect(self, ssid, pw):*
*"""*
*Connect to Access point using SSID and PW.*

*:param ssid: SSID of the ACCESS POINT.*
*:param pw: password for connecting to the access point.*
*:return: command output as True or False.*
*"""*

*cmd = "nmcli -t -f TYPE,UUID con"*
*res = self._helper.execute_cmd_output_string(cmd)*
*print(res)*
*lines = res[1].split('\n') > I suspect the
issue might be here*
*print(lines)*

*for line in lines:*
*parts = line.split(":")*
*print(parts)*
*print(parts[1])*
*if (parts[0] == "802-11-wireless"):*
*print("nmcli connection delete uuid "+ parts[1])*
*os.system("nmcli connection delete uuid "+ parts[1])*

*cmd = "nmcli device wifi connect '%s' password %s" % (ssid, pw)*
*exit_code = self._helper.execute_cmd_return_code(cmd)*

*return True if exit_code == 0 else False*


def execute_cmd_output_string(self, cmd, enable_shell=False):
"""
Execute a command and return its output as a string.

:param cmd: abs path of the command with arguments
:param enable_shell : force the cmd to be run as shell script
:return: a string.
"""

try:
result = subprocess.check_output(split(cmd),
 stderr=subprocess.STDOUT,
 shell=enable_shell)

except subprocess.CalledProcessError as e:
s = """While executing '{}' something went wrong.
Return code == '{}'
Return output:\n'{}'
""".format(cmd, e.returncode, e.output, shell=enable_shell)
raise AssertionError(s)

return result.strip().decode("utf-8")


if __name__ == "__main__":
m = wifi()
print("disconnect and reconnect")
print(m.wifi_disconnect_reconnect("NaWiFi", "abcds"))


*Errors:*
---
Traceback (most recent call last):
802-11-wireless:3f5011d4-5681-4fed-8dea-95dee790e9e2
802-11-wireless:dc2a15ec-d3da-491e-9c8f-cb054f375837
802-11-wireless:5164e7f2-4489-462e-b093-76bc51bf1303
  File
"/home/srinivasan/Downloads/qa_wifi_nov15_after_incorporating_thilo_comments_zip/qa/test_library/wifi.py",
line 153, in 
802-11-wireless:d462e8c4-fac7-42f2-8f9a-6846f52d4e8c
print(m.wifi_connect("NI WiFi", "T.f.o.s.1996!"))
802-11-wireless:e5020744-5c9c-453c-92ec-7a854fc893e6
802-11-wireless:eed3358e-8635-471d-b7e9-5c2973a05128
  File
"/home/srinivasan/Downloads/qa_wifi_nov15_after_incorporating_thilo_comments_zip/qa/test_library/wifi.py",
line 77, in wifi_connect
802-11-wireless:ceea6707-a929-4941-9047-a75e061914b

[Tutor] Cannot find reference 'bluetoothctl' in 'sh.py' less... (Ctrl+F1)

2018-11-14 Thread srinivasan
Dear Python Experts,

As am newbie to python, I am planning to automate BT functionality test
using Bluez "bluetoothctl" utility  by writing python wrapper and robot
framework integrated with Jenkins

I came across the below link:
https://www.reddit.com/r/raspberry_pi/comments/4bxu2o/bluetoothctl_in_python_program/

In the above link, I saw the below code snippet
*code:*

*from sh import bluetoothctl*
*mac = "AA:BB:CC:DD:EE"*
*bluetoothctl("connect",mac)*


And firstly I wanted to verify BT functionality with my PC and the
bluetooth device (basically turned on BT option in my phone and trying to
discover my phone as a BT device) And I have installed the below packages
in my ubuntu 18.04 desktop PC
$* pip3 install sh*
Collecting sh
  Downloading
https://files.pythonhosted.org/packages/4a/22/17b22ef5b049f12080f5815c41bf94de3c229217609e469001a8f80c1b3d/sh-1.12.14-py2.py3-none-any.whl
Installing collected packages: sh
Successfully installed sh-1.12.14
*$ pip3 install bluetoothctl*
*Collecting bluetoothctl*
*  Could not find a version that satisfies the requirement bluetoothctl
(from versions: )*
*No matching distribution found for bluetoothctl*
$ *pip3 install pexpect*
Collecting pexpect
  Downloading
https://files.pythonhosted.org/packages/89/e6/b5a1de8b0cc4e07ca1b305a4fcc3f9806025c1b651ea302646341222f88b/pexpect-4.6.0-py2.py3-none-any.whl
(57kB)
100% || 61kB 1.5MB/s
Collecting ptyprocess>=0.5 (from pexpect)
  Downloading
https://files.pythonhosted.org/packages/d1/29/605c2cc68a9992d18dada28206eeada56ea4bd07a239669da41674648b6f/ptyprocess-0.6.0-py2.py3-none-any.whl
Installing collected packages: ptyprocess, pexpect
Successfully installed pexpect-4.6.0 ptyprocess-0.6.0
$

When I try to paste the below code on pycharm and try to point on the word
"bluetoothctl" in the beginning of the line "*from sh import bluetoothctl*"

*from sh import bluetoothctl*

*mac = "your bluetooth mac"*
*bluetoothctl("connect", mac)*

In the pycharm, I see the below error message :

*Cannot find reference 'bluetoothctl' in 'sh.py' less... (Ctrl+F1) *
*Inspection info: This inspection detects names that should resolve but
don't. Due to dynamic dispatch and duck typing, this is possible in a
limited but useful number of cases. Top-level and class-level items are
supported better than instance items.*

Could you please help me to resolve the above issue, like why am I seeing
the above issue it seems to be some importing "bluetoothhctl" module issue
(sorry if my understanding is wrong)

Kindly do the needful
Many Thanks in advance
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] All of a sudden code started throwing errors

2018-11-14 Thread srinivasan
Dear Python Experts

Could you please let me know why am I seeing the following errors as before
this it was working consistently?



root:~/qa/robot_tests# python3 -m robot --variable
SIGNAL_LEVEL_THRESHOLD:-60 wifi_testing.robot
==
Wifi Testing :: This is the Maschine Native OS Build Wi-Fi Test.

==
Initialize Wi-Fi Module   |
PASS |
--
Enable Wi-Fi Module   |
PASS |
--
Connect Wi-Fi Module to SSID  |
PASS |
--
Check for Wi-Fi Connectivity  |
PASS |
--
Log Wi-Fi Module IP   |
PASS |
--
Get Gateway IP and Check Whether Wi-Fi is Pingable|
PASS |
--
Check for Wi-Fi Signal Strength with Threshold|
FAIL |
'-68 >= -60' should be true.
--
Wifi Testing :: This is the Maschine Native OS Build Wi-Fi Test.  |
FAIL |
7 critical tests, 6 passed, 1 failed
7 tests total, 6 passed, 1 failed
==
Output:  /home/root/qa/robot_tests/output.xml
Log: /home/root/qa/robot_tests/log.html
Report:  /home/root/qa/robot_tests/report.html
root:~/qa/robot_tests# cat /proc/net/wireless
Inter-| sta-|   Quality|   Discarded packets   | Missed
| WE
 face | tus | link level noise |  nwid  crypt   frag  retry   misc | beacon
| 22
wlp1s0:    44.  -66.  -2560  0  0  0  90



Errors:
=


root:~/qa/robot_tests# python3 -m robot --variable
SIGNAL_LEVEL_THRESHOLD:-70 wifi_testing.robot
Traceback (most recent call last):
  File "/usr/lib/python3.5/runpy.py", line 183, in _run_module_as_main
mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
  File "/usr/lib/python3.5/runpy.py", line 142, in _get_module_details
return _get_module_details(pkg_main_name, error)
  File "/usr/lib/python3.5/runpy.py", line 109, in _get_module_details
__import__(pkg_name)
  File "/usr/lib/python3.5/site-packages/robot/__init__.py", line 41, in

from robot.rebot import rebot, rebot_cli
  File "/usr/lib/python3.5/site-packages/robot/rebot.py", line 40, in

from robot.conf import RebotSettings
  File "/usr/lib/python3.5/site-packages/robot/conf/__init__.py", line 27,
in 
from .settings import RobotSettings, RebotSettings
  File "/usr/lib/python3.5/site-packages/robot/conf/settings.py", line 33,
in 
class _BaseSettings(object):
  File "/usr/lib/python3.5/site-packages/robot/conf/settings.py", line 46,
in _BaseSettings
'OutputDir': ('outputdir', abspath('.')),
  File "/usr/lib/python3.5/site-packages/robot/utils/robotpath.py", line
84, in abspath
return normpath(_abspath(path), case_normalize)
  File "/usr/lib/python3.5/posixpath.py", line 362, in abspath
cwd = os.getcwd()
FileNotFoundError: [Errno 2] No such file or directory
root:~/qa/robot_tests# cat /proc/net/wireless
Inter-| sta-|   Quality|   Discarded packets   | Missed
| WE
 face | tus | link level noise |  nwid  crypt   frag  retry   misc | beacon
| 22
wlp1s0:    45.  -65.  -2560  0  0  0 120
root:~/qa/robot_tests# python3 -m robot wifi_testing.robot

Traceback (most recent call last):
  File "/usr/lib/python3.5/runpy.py", line 183, in _run_module_as_main
mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
  File "/usr/lib/python3.5/runpy.py", line 142, in _get_module_details
return _get_module_details(pkg_main_name, error)
  File "/usr/lib/python3.5/runpy.py", line 109, in _get_module_details
__import__(pkg_name)
  File "/usr/lib/python3.5/site-packages/robot/__init__.py", line 41, in

from robot.rebot import rebot, rebot_cli
  File "/usr/lib/python3.5/site-packages/robot/rebot.py", line 40, in

from robot.conf import RebotSettings
  File "/usr/lib/python3.5/site-packages/robot/conf/__init__.py", line 27,
in 
from .settings import RobotSettings, RebotSettings
  File "/usr/lib/python3.5/site-packages/robot/conf/settings.py", line 33,
in 
class _BaseSettings(object):
  File "/usr/lib/python3.5/site-packages/robot/conf/settings.py", line 46,
in _BaseSettings
'OutputDir': ('outputdi

[Tutor] Unable to get the gateway IP of wlan interface using python code

2018-11-12 Thread srinivasan
Dear Python Experts,

*First method:*

I need to get the IP address basically the gateway IP in my setup I get it
as "192.168.178.1" when I run the below standalone python code.


*def get_gateway_ip(self):*
*"""*
*Get the IP address to the WIFI module from the AP*
*"""*

*cmd = 'ip route show 0.0.0.0/0  dev wlp1s0 | cut
-d\  -f3'*
*f = os.popen(cmd)*
*return str(f.read().strip())*


I am trying to log the IP in the robot framework script and ensure that my
router is able to ping but "*${SSID_GATEWAY_IP}*" doesn't seem to get
collected from the above python code and pass this value to my custom
method "*Wait Until Device Is Pingable"*

*${RET} =Wait Until Device Is Pingable ${SSID_GATEWAY_IP}*
*Should Be True${RET}*

But whenever I hardcode the "*${SSID_GATEWAY_IP}  192.168.178.1*" in the
robot framework, it seems to be working with "*Wait Until Device Is
Pingable ${SSID_GATEWAY_IP}*"

But the below robot framework script doesn't seems to work with the return
value received from the above python script, could you please do the
needful?

*Get Gateway IP of SSID*
* ${SSID_GATEWAY_IP} = Get Gateway Ip*
* Log  ${SSID_GATEWAY_IP}*
*${RET} =Wait Until Device Is Pingable ${SSID_GATEWAY_IP}*
*Should Be True${RET}*


*SECOND METHOD:*

When I use the subprocess I see the below issue:



def get_gateway_ip(self):
"""
Get the IP address to the WIFI module from the AP
"""

#cmd = 'ip route show 0.0.0.0/0 dev wlp1s0 | cut -d\  -f3'
# f = os.popen(cmd)
# return str(f.read().strip())


p = subprocess.Popen('ip route show 0.0.0.0/0 dev wlp1s0 | cut -d\
-f3', stdout=subprocess.PIPE)
result = p.communicate()[0]
print(result)

#list = os.popen('ip route show 0.0.0.0/0 dev wlp1s0 | cut -d\
-f3').read()

# p = Popen(cmd, shell=True, stdout=PIPE)
# out, err = p.communicate()
# #return (p.returncode, out, err)
# return out
# #print('returncode: %s' % result[0])
# #print('output: %s' % result[1])
# #print('error: %s' % result[2])

#return self._helper.execute_cmd_output_string(cmd)


Error:

root:~/qa/test_library# python3 wifi.py
Enabling wifi
Verify wifi connectivity
True
Get gateway wifi ip
Traceback (most recent call last):
  File "wifi.py", line 134, in 
print(m.get_gateway_ip())
  File "wifi.py", line 76, in get_gateway_ip
p = subprocess.Popen('ip route show 0.0.0.0/0 dev wlp1s0 | cut -d\
-f3', stdout=subprocess.PIPE)
  File "/usr/lib/python3.5/subprocess.py", line 676, in __init__
restore_signals, start_new_session)
  File "/usr/lib/python3.5/subprocess.py", line 1289, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'ip route show
0.0.0.0/0 dev wlp1s0 | cut -d\\  -f3'
root:~/qa/test_library#


As I am stuck with this issue from past 2 days, wondering for any clues

Kindly do the needful as early as possible

Many Thanks in adavnce
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Issue in parsing the strings in python code

2018-11-12 Thread srinivasan
Dear Python Experts team,

This question might be very simple for you, As am newbie to python, could
you please how to parse the below strings

1. Could you please do the needful in guiding me, that how can I extract
the strings under the UUID column in python code in the below output (nmcli
c show), I need to extract the UUID of "Funkloch" ie.,
"1da7d068-4548-4446-bf88-a440e49db1b1" for "TYPE" wifi and device "wlp1s0"
and return this string ("1da7d068-4548-4446-bf88-a440e49db1b1") to the
robotframework?


root:~/qa/robot_tests# nmcli c show
NAMEUUID  TYPE  DEVICE

Funkloch 1552 c8e1e8c0-0f25-4299-a9ae-2910cfef2ebd  wifi  wlp1s0

Wired connection 1  2a14fbe6-58a0-3b7f-b986-5d1b36a94ec0  ethernet
enp0s21f0u4
Funkloch  1da7d068-4548-4446-bf88-a440e49db1b1  wifi  --

Funkloch 10   f4d9ce13-aab0-4485-9929-6070ad52a196  wifi  --

Funkloch 100  8b48a220-1754-4988-84ad-d0f83a9b4ede  wifi  --



2. Similarly, As I need to verify whether the DEVICE "wlp1s0" is connected
to "Funkloch" or not? could you please help me, how can I extract the
"connected" status under "STATE column for DEVICE "wlp1s0" and CONNECTION
"Funkloch 1552"

root:~/qa/robot_tests# nmcli dev
DEVICE   TYPE  STATECONNECTION
enp0s21f0u4  ethernet  connectedWired connection 1
wlp1s0   wifi  connectedFunkloch 1552
enp2s0   ethernet  unavailable  --
sit0 iptunnel  unmanaged--
lo   loopback  unmanaged--

Kindly do the needful as am trying this from past two 2 days, still no clues

Many thanks in advance
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] best way to dynamically set class variables?

2018-11-08 Thread srinivasan
Once again thanks a lot guys for all your help and I really appreciate it
that I can really come back to you, if am stuck with any python issues, as
i was really a embedded linux platform developer

>From now I have learnt not to use much bash commands with pipe and to just
use the bash command and parse it using python code

For now I have simplified and it working as below, might be useful for
others sometime


def get_fstype_of_mounted_partition(self, partition_path):
"""
Get the filesystem type of the mounted partition.

:partition_name : Partition path as string (e.g. /dev/mmcblk0p1)
:return: filesystem type as string
"""

cmd = "lsblk %s -n -o FSTYPE" % partition_path
return self._helper.execute_cmd_output_string(cmd)

On Thu, Nov 8, 2018 at 11:11 AM Avi Gross  wrote:

> I have been reading the replies and wonder sometimes if we understand the
> real question as intended.
>
> Classes in Python can be changed in all kinds of ways even after they have
> been defined and the changes take effect on any new instances created
> afterward. So can instances in multiple ways. If you want to store the
> names
> of a hundred columns in a variable or even a hundred variables, you have
> ways to assign them. You can even change methods on the fly.
>
> If what you want is even more flexibility to design the class later after
> receiving more data such as the names and types of the columns in a data
> table, you can either write the description as text into a temporary file
> and import it, if that makes sense, or make a string to be evaluated in
> memory. Both can be dangerous if you do not trust the parts added as the
> code is going to be run at runtime and can do malicious things.
>
> Python often has so many ways to do things that various ones may work
> better
> for you. In your case, one example would be to intercept the ability to set
> and get (unknown) components of a class or instance by using the right
> dunder function such as __getattr__ and have it KNOW about your dynamic
> variable names and control access to them. There are many ways to do this,
> CAREFULLY, and some work only or differently in new style classes. Heck,
> you
> can put all the important code in an external function called by the above
> that can dynamically be made in Python at a later time. One architecture
> might be to store your new info in one or more dictionaries and have that
> functionality check if a valid request is made and return it. Obviously it
> matters where you want the data held as in per instance or per class or
> superclass and so on.
>
> Of course, I may misunderstand your issue. But from what it sounds like,
> your main request is a way to associate multiple items to be stored after a
> class is created but before it is used. There are an amazing number of ways
> even before you loom at more advanced methods like decorators.
>
> -Original Message-
> From: Tutor  On Behalf Of
> Oscar Benjamin
> Sent: Wednesday, November 7, 2018 5:33 PM
> To: tutor@python.org
> Subject: Re: [Tutor] best way to dynamically set class variables?
>
> On Wed, 7 Nov 2018 at 18:35, Alan Gauld via Tutor 
> wrote:
> >
> > On 07/11/2018 14:48, Albert-Jan Roskam wrote:
> >
> > > What is the best way to dynamically set class variables?
> >
> > I think I'm maybe missing the point of your question?
>
> I think you are as well :)
>
> IIUC then the question is: how can I programatically/dynamically create a
> class that has some attributes derived from data that is known at runtime?
>
> Am I understanding this correctly Albert?
>
> > > # ---
> > > class Parent: pass
> > > class_vars = dict(col1='str', col2='int')
> > >
> > > # approach 1
> > > Child = type('Child', (Parent,), class_vars)
>
> This seems fine to me. It may seem cryptic but that's only because it's
> unusual to do this. You are creating a "type" and that is the constructor
> for type objects.
>
> --
> Oscar
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] SyntaxError: can't assign to literal while using ""blkid -o export %s | grep 'TYPE' | cut -d"=" -f3" % (fs)" using subprocess module in Python

2018-11-07 Thread srinivasan
Even after changing as per the below
"blkid -o export %s | grep 'TYPE' | cut -d'=' -f3"
or:
'blkid -o export %s | grep "TYPE" | cut -d"=" -f3'
or:
"blkid -o export %s | grep \"TYPE\" | cut -d\"=\" -f3"

Still my output is:
*/dev/mmcblk1p1: LABEL="efi" UUID="1084-AA42" TYPE="vfat"*

My expected output should be only:
*vfat*

Could you guys please do the needful?


On Wed, Nov 7, 2018 at 11:10 AM Brian J. Oney 
wrote:

> On Wed, 2018-11-07 at 10:22 +0100, srinivasan wrote:
> > blkid -o export %s | grep \'TYPE\' | cut -d\"=\" -f3
>
> You don't need to escape the single quotes.
> Try either:
>
> "blkid -o export %s | grep 'TYPE' | cut -d'=' -f3"
> or:
> 'blkid -o export %s | grep "TYPE" | cut -d"=" -f3'
> or:
> "blkid -o export %s | grep \"TYPE\" | cut -d\"=\" -f3"
>
> HTH
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] SyntaxError: can't assign to literal while using ""blkid -o export %s | grep 'TYPE' | cut -d"=" -f3" % (fs)" using subprocess module in Python

2018-11-07 Thread srinivasan
After changing the line to *"cmd = "blkid -o export %s | grep \'TYPE\' |
cut -d\"=\" -f3" % fs"*, Now I dont see the error "SyntaxError: can't
assign to literal"
This is not returning exactly "*vfat*" instead of this, it is returning as "*
/dev/mmcblk1p1: LABEL="efi" UUID="1084-AA42" TYPE="vfat"* "

Could you please help me  as it seems to be like grep and cut commands are
not working in the above line ie., on *cmd = "blkid -o export %s | grep
\'TYPE\' | cut -d\"=\" -f3" % fs*?

On Wed, Nov 7, 2018 at 9:41 AM Avi Gross  wrote:

> I may be missing something but it looks like the embedded double quotes
> may be a problem in this:
>
> cmd = "blkid -o export %s | grep 'TYPE' | cut -d"=" -f3" % ...
>
> if you use single quotes as in:
>
> cut -d"="
>
> becomes
>
> cut -d'='
>
> or escape the double quotes with \" and so on ...
>
> The above seems to be seen as:
>
> cmd=ALPHA=BETA % ...
>
> where ALPHA="blkid -o export %s | grep 'TYPE' | cut -d"
> and BETA=" -f3"
>
> Other issues may also be there.
> -Original Message-
> From: Tutor  On Behalf Of
> Alan Gauld via Tutor
> Sent: Tuesday, November 6, 2018 7:37 PM
> To: tutor@python.org
> Cc: python-...@python.org
> Subject: Re: [Tutor] SyntaxError: can't assign to literal while using
> ""blkid -o export %s | grep 'TYPE' | cut -d"=" -f3" % (fs)" using
> subprocess module in Python
>
> On 06/11/2018 18:07, srinivasan wrote:
>
> > bash command in python using subprocess module, I ma seeing the below
> > *cmd = "blkid -o export %s | grep 'TYPE' | cut -d"=" -f3" %
> > (fs)*
>
> In general you should try to do as little as possible using bash and
> subprocess. Especially try to avoid long pipelines since you are starting a
> new OS process for every element in the pipeline. That means, in your case,
> you are running 4 processes to get your result - Python, blkid, grep and cut
>
> Python is designed to do much of what the shell command can do almost as
> easily and much more efficiently (no new processes being started).
>
> In this case just execute the blkid bit in bash because its too difficult
> to replicate simply in Python. Then use Python to search for the TYPE lines
> and slice them to size.
>
> That will, in turn, simplify your command string and remove the issue of
> multiple quotes.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] SyntaxError: can't assign to literal while using ""blkid -o export %s | grep 'TYPE' | cut -d"=" -f3" % (fs)" using subprocess module in Python

2018-11-06 Thread srinivasan
Dear Python Experts Team,

As am newbie to python development, I am trying to use the below function
to get verify the filesystem type of the SD card parition using bash
command in python using subprocess module, I ma seeing the below Error
"SyntaxError: can't assign to literal"

*CODE:*
**

import helper
from os import path
import subprocess
import os
import otg_ni


class emmc(object):
"""
emmc getters and setters
info:
https://www.kernel.org/doc/Documentation/cpu-freq/user-guide.txt
"""

def __init__(self):
self._helper = helper.helper()
self._otg_ni = otg_ni.otg_ni()


*def get_fstype_of_mounted_partition(self, fs):*
"""
Get the filesystem type of the mounted partition.

:partition_name : Partition path as string (e.g. /dev/mmcblk0p1)
:return: filesystem type as string or None if not found
"""

*cmd = "blkid -o export %s | grep 'TYPE' | cut -d"=" -f3" % (fs)*
*return self._helper.execute_cmd_output_string(cmd)*



*def execute_cmd_output_string(self, cmd, enable_shell=False):*
"""
Execute a command and return its output as a string.

:param cmd: abs path of the command with arguments
:param enable_shell : force the cmd to be run as shell script
:return: a string.
"""

try:
result = subprocess.check_output(split(cmd),
 stderr=subprocess.STDOUT,
 shell=enable_shell)

except subprocess.CalledProcessError as e:
s = """While executing '{}' something went wrong.
Return code == '{}'
Return output:\n'{}'
""".format(cmd, e.returncode, e.output, shell=enable_shell)
raise AssertionError(s)

return result.strip().decode("utf-8")
*if __name__ == "__main__":*
m = emmc()
*m.get_fstype_of_mounted_partition("/dev/mmcblk0p1")*
*Error:*
*==*

root:~/qa/test_library# python3 sd.py
  File "sd.py", line 99
*cmd = "blkid -o export %s | grep 'TYPE' | cut -d"=" -f3" % (fs)*
* ^*
*SyntaxError: can't assign to literal*
root:~/qa/test_library#

Kindly do the needful as early as possible, as am stuck with this issue
from past 2 days no clues yet, please redirect me to the correct forum if
this is not the right place for pasting python related queries

Many Thanks in advance,
Srini
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Binary chop function - this works, but I'm not sure why

2008-02-14 Thread Arun Srinivasan
On Thu, Feb 14, 2008 at 11:41 AM, Arun Srinivasan
<[EMAIL PROTECTED]> wrote:
>
> On Thu, Feb 14, 2008 at 5:27 AM, bob gailer <[EMAIL PROTECTED]> wrote:
>  >
>  > Arun Srinivasan wrote:
>  > > I'm trying to learn Python, and I decided to try kata 2  from the
>  > > CodeKate website. It's basically just a challenge to implement a
>  > > binary search in different ways.
>  > >
>  > > I wrote an implementation that works, but I'm confused as to why.
>  > >
>  > > def chop(search_int, sorted_list):
>  > > if len(sorted_list) == 1 or 2:
>  > Yet another way to express that is:
>  >
>  >   if 1 <= len(sorted_list) <= 2:
>  >
>  > > for x in sorted_list:
>  > > if x == search_int:
>  > > return sorted_list.index(x)
>  > > return -1
>  > >
>  > > midpoint = (len(sorted_list) - 1) / 2
>  > > mp_value = sorted_list[midpoint]
>  > >
>  > > if mp_value == search_int:
>  > > return midpoint
>  > > elif mp_value > search_int:
>  > > return chop(search_int, sorted_list[:midpoint])
>  > > else:
>  > > return chop(search_int, sorted_list[midpoint + 1:])
>  > >
>  > > Basically, it only returns the index if it matches in the if statement
>  > > at the beginning of the function, but since that is limited to lists
>  > > of length 2 or 1, why doesn't it return only 0 or 1 as the index? I
>  > > think there is something about recursion here that I'm not fully
>  > > comprehending.
>  > >
>  > >
>  > >
>  > > 
>  > >
>  > > ___
>  > > Tutor maillist  -  Tutor@python.org
>  > > http://mail.python.org/mailman/listinfo/tutor
>  > >
>  >
>  >
>  > --
>  > Bob Gailer
>  > 919-636-4239 Chapel Hill, NC
>  >
>  >
>
>  Oy, I should have seen that. Thanks for the responses - time to go
>  back and fix this.
>

Turns out it was simple to fix - just needed to fix that test so it
wasn't silly, add the lower bound tracking (thanks Alan), and make
sure to test for empty lists. Here's the function in all (rather, what
little there is) of its glory:

def chop(search_int, sorted_list, lbound = 0):
if len(sorted_list) == 0:
return -1

if len(sorted_list) in [1,2]:
if sorted_list[0] == search_int: return lbound
elif len(sorted_list) == 2 and  sorted_list[1] == search_int:
return lbound + 1
else: return -1

midpoint = (len(sorted_list) - 1) / 2
mp_value = sorted_list[midpoint]

if mp_value == search_int:
return midpoint
elif mp_value > search_int:
return chop(search_int, sorted_list[:midpoint])
else:
return chop(search_int, sorted_list[midpoint + 1:], lbound +
midpoint + 1)

Alan, could you please explain why

if sorted_list[0] == search_int: return 0
elif len(sorted_list) == 2 and  sorted_list[1] == search_int: return 1
else: return -1

is faster than:

>for x in sorted_list:
>if x == search_int:
>return sorted_list.index(x)
>return -1

Thanks for the help!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Binary chop function - this works, but I'm not sure why

2008-02-14 Thread Arun Srinivasan
On Thu, Feb 14, 2008 at 5:27 AM, bob gailer <[EMAIL PROTECTED]> wrote:
>
> Arun Srinivasan wrote:
> > I'm trying to learn Python, and I decided to try kata 2  from the
> > CodeKate website. It's basically just a challenge to implement a
> > binary search in different ways.
> >
> > I wrote an implementation that works, but I'm confused as to why.
> >
> > def chop(search_int, sorted_list):
> > if len(sorted_list) == 1 or 2:
> Yet another way to express that is:
>
>   if 1 <= len(sorted_list) <= 2:
>
> > for x in sorted_list:
> > if x == search_int:
> > return sorted_list.index(x)
> > return -1
> >
> > midpoint = (len(sorted_list) - 1) / 2
> > mp_value = sorted_list[midpoint]
> >
> > if mp_value == search_int:
> > return midpoint
> > elif mp_value > search_int:
> > return chop(search_int, sorted_list[:midpoint])
> > else:
> > return chop(search_int, sorted_list[midpoint + 1:])
> >
> > Basically, it only returns the index if it matches in the if statement
> > at the beginning of the function, but since that is limited to lists
> > of length 2 or 1, why doesn't it return only 0 or 1 as the index? I
> > think there is something about recursion here that I'm not fully
> > comprehending.
> >
> >
> >
> > 
> >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
> --
> Bob Gailer
> 919-636-4239 Chapel Hill, NC
>
>

Oy, I should have seen that. Thanks for the responses - time to go
back and fix this.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Binary chop function - this works, but I'm not sure why

2008-02-13 Thread Arun Srinivasan
I'm trying to learn Python, and I decided to try kata 2  from the
CodeKate website. It's basically just a challenge to implement a binary
search in different ways.

I wrote an implementation that works, but I'm confused as to why.

def chop(search_int, sorted_list):
if len(sorted_list) == 1 or 2:
for x in sorted_list:
if x == search_int:
return sorted_list.index(x)
return -1

midpoint = (len(sorted_list) - 1) / 2
mp_value = sorted_list[midpoint]

if mp_value == search_int:
return midpoint
elif mp_value > search_int:
return chop(search_int, sorted_list[:midpoint])
else:
return chop(search_int, sorted_list[midpoint + 1:])

Basically, it only returns the index if it matches in the if statement at
the beginning of the function, but since that is limited to lists of length
2 or 1, why doesn't it return only 0 or 1 as the index? I think there is
something about recursion here that I'm not fully comprehending.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor