No module named 'src' - module

from src.myodriver import MyoDriver
from src.config import Config
from src.Data_preparation import Data_preparation as dp
from src.data_handler import DataHandler as dh
import serial
import getopt
import sys
import time
I got no module named 'src'
Can someone explain it to me?
I also made this
pip install src==0.0.6
But i got "Failed building wheel for src"
I was trying to make this work.
def temps():
temps = time.time()
return(temps)
def main(argv):
config = Config()
# Get options and arguments
try:
opts, args = getopt.getopt(argv, 'hsn:a:p:v', ['help', 'shutdown', 'nmyo', 'address', 'port', 'verbose'])
except getopt.GetoptError:
sys.exit(2)
turnoff = False
for opt, arg in opts:
if opt in ('-h', '--help'):
print_usage()
sys.exit()
elif opt in ('-s', '--shutdown'):
turnoff = True
elif opt in ("-n", "--nmyo"):
config.MYO_AMOUNT = int(arg)
elif opt in ("-a", "--address"):
config.OSC_ADDRESS = arg
elif opt in ("-p", "--port"):
config.OSC_PORT = arg
elif opt in ("-v", "--verbose"):
config.VERBOSE = True
# Run
myo_driver = None
try:
# Init
myo_driver = MyoDriver(config)
# Connect
myo_driver.run()
if turnoff:
# Turn off
myo_driver.deep_sleep_all()
return
if Config.GET_MYO_INFO:
# Get info
myo_driver.get_info()
print("Ready for data.")
print()
#Chronomètre et affichage
temps = time.time()
y = time.time()-temps
réinitialisation_chrono = 1
while (y<126):
y = time.time()-temps
dp.print_action(dp.action_case(y))
# Receive and handle data
#Kwhile True:
myo_driver.receive()
time.sleep(0.02) #Reduces CPU usage
print(y)
dp.add_label_and_define_time("test_1_data.csv","Data_3.csv")
except KeyboardInterrupt:
print("Interrupted.")
except serial.serialutil.SerialException:
print("ERROR: Couldn't open port. Please close MyoConnect and any program using this serial port.")
finally:
print("Disconnecting...")
if myo_driver is not None:
if Config.DEEP_SLEEP_AT_KEYBOARD_INTERRUPT:
myo_driver.deep_sleep_all()
else:
myo_driver.disconnect_all()
print("Disconnected")
def print_usage():
message = """usage: python mio_connect.py [-h | --help] [-s | --shutdown] [-n | --nmyo ] [-a | --address \
] [-p | --port ] [-v | --verbose]
Options and arguments:
-h | --help: display this message
-s | --shutdown: turn off (deep_sleep) the expected amount of myos
-n | --nmyo : set the amount of devices to expect
-a | --address : set OSC address
-p | --port : set OSC port
-v | --verbose: get verbose output
"""
print(message)
if name == "main":
main(sys.argv[1:])

Related

iothub_registry_manager_bulk_create_sample

I am trying to run below code in Visual Studio:
import sys
import os
from azure.iot.hub import IoTHubRegistryManager
from azure.iot.hub.models import ExportImportDevice, AuthenticationMechanism, SymmetricKey
iothub_connection_str = "HostName=bulkdevice.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=YsKedao6li9wKbpMC5sJftPXNhB0km6Jt6bAD3KqBes="
try:
# Create IoTHubRegistryManager
iothub_registry_manager = IoTHubRegistryManager(iothub_connection_str)
# primary_key1 = "aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnoo"
# secondary_key1 = "111222333444555666777888999000aaabbbcccdddee"
# symmetric_key1 = SymmetricKey(
# primary_key=primary_key1, secondary_key=secondary_key1)
# authentication1 = AuthenticationMechanism(
# type="sas", symmetric_key=symmetric_key1)
device1 = ExportImportDevice(
id="BulkDevice1")
# primary_key2 = "cccbbbaaadddeeefffggghhhiiijjjkkklllmmmnnnoo"
# secondary_key2 = "333222111444555666777888999000aaabbbcccdddee"
# symmetric_key2 = SymmetricKey(
# primary_key=primary_key2, secondary_key=secondary_key2)
# authentication2 = AuthenticationMechanism(
# type="sas", symmetric_key=symmetric_key2)
device2 = ExportImportDevice(
id="BulkDevice2")
# Create devices
device1.import_mode = "create"
device2.import_mode = "create"
device_list = [device1, device2]
iothub_registry_manager.bulk_create_or_update_devices(device_list)
# Get devices (max. 1000 with get_devices API)
# max_number_of_devices = 10
# devices = iothub_registry_manager.get_devices(max_number_of_devices)
# if devices:
# x = 0
# for d in devices:
# print_device_info("Get devices {0}".format(x), d)
# x += 1
# else:
# print("No device found")
# Delete devices
# device1.import_mode = "delete"
# device2.import_mode = "delete"
# device_list = [device1, device2]
# iothub_registry_manager.bulk_create_or_update_devices(device_list)
except Exception as ex:
print("Unexpected error {0}".format(ex))
except KeyboardInterrupt:
print("iothub_registry_manager_sample stopped")
I am getting an error unable to register multiple devices in IoThub, please help me register.

SyntaxError: unexpected EOF while parsing - tn.close()

Need to write some code for work that telnets into a device, runs a command and exits telnet
I Keep getting error
file "python", line 54
tn.close()
^
SyntaxError: unexpected EOF while parsing
What am I doing wrong, new to coding
Cheers
import time
import telnetlib
tn_username = "xxxx"
tn_password = "xxxxxxx"
#Globals:
CACHE_DATA = {}
SNIPPET_NAME = 'xxxxxx: xxxxxx'
FAILED_COUNT = 0
COLLECTION_PROBLEM = False
TELNET_PORT = 23
TELNET_TIMEOUT = 2
FAILED_ITEMS = []
self.logger.ui_debug('************** %s: Starting *******************' % (SNIPPET_NAME))
#start timer
start_time = time.time()
try:
#connect to telnet
tn = telnetlib.Telnet
tn.read_until("login: ")
tn.write(tn_username + "\n")
tn.read_until("Password: ")
tn.write(tn_password + "\n")
for obj_oid in result_handler.oids:
##obj_name = result_handler[obj_oid]['name']
try:
#run oid as CLI call from result_handler
tn.write(obj_oid+"\r")
rawdata = tn.read_until("Welcome to the Tesira Text Protocol Server...", TELNET_TIMEOUT)
if rawdata:
result_handler[obj_oid] = [(0,"Collection Ok")]
CACHE_DATA[obj_oid] = rawdata.strip()
else:
FAILED_COUNT += 1
result_handler[obj_oid] = [(0,"Failed: No data found")]
FAILED_ITEMS.append(obj_oid)
except:
FAILED_ITEMS.append(obj_oid)
result_handler[obj_oid] = [(0,'Failed: Collection: %s' % obj_oid)]
FAILED_COUNT +=1
#save job time for perf graph
CACHE_DATA['biamp'] = round(time.time() - start_time,4)
#gracefully quit the telnet session so as to not leave any defunct processes on the host device.
tn.write("bye\r")
tn.close()

python3.5 paramiko failed with hostname

Please help me to correct my script. My script checks the ssh login of a host and displays success/failure based on result. It fails when I give wrong hostname.
Code is as of below :
[root#test1 script]# cat param.py
import multiprocessing
import paramiko
import random
import threading
import time
host_name = "test2"
print ("Checking hostname :"+str(host_name))
file = open('output_file','a')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host_name, username='root', password='test')
print ("success")
file.write("success:"+str(host_name+"\n"))
except paramiko.SSHException:
print ("Connection Failed")
file.write("failed:"+str(host_name+"\n"))
quit()
stdin,stdout,stderr = ssh.exec_command("hostname&&uptime")
for line in stdout.readlines():
print (line.strip())
ssh.close()
It works fine when the correct username/password given :
[root#test1 script]# python3 param.py
Checking hostname :test2
success
test2
12:31:49 up 83 days, 2:56, 2 users, load average: 0.00, 0.01, 0.05
It works fine when the wrong password is given. I have changed the password to a wrong one in the script and it says connection failed as expected.
root#test1 script]# python3 param.py
Checking hostname :test2
Connection Failed
Now my question, when I change the hostname to something doenot exist, paramiko fails and lot of errors pop up.
[root#test1 script]# python3 param.py
Checking hostname :invalidtest2
Traceback (most recent call last):
File "param.py", line 16, in <module>
ssh.connect(host_name, username='root', password='test')
File "/root/usr/local/lib/python3.5/site-packages/paramiko/client.py", line 301, in connect
to_try = list(self._families_and_addresses(hostname, port))
File "/root/usr/local/lib/python3.5/site-packages/paramiko/client.py", line 199, in _families_and_addresses
hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
File "/root/usr/local/lib/python3.5/socket.py", line 728, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
How can I get message that the connection failed ? I'm using python3.5
It is not good idea to keep the passwords stored in the script itself. Modified the script so that it takes the hostnames from a file and writes the output to different files
#!/bin/python3
import threading, time, paramiko, socket, getpass
from queue import Queue
start_time1 = time.time()
locke1 = threading.Lock()
q = Queue()
#Check the login
def check_hostname(host_name, pw_r):
with locke1:
print ("Checking hostname :"+str(host_name)+" with " + threading.current_thread().name)
file_output = open('output_file','a')
file_success = open('success_file','a')
file_failed = open('failed_file','a')
file_error = open('error_file','a')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host_name, username='root', password=pw_r)
#print ("Success")
file_success.write(str(host_name+"\n"))
file_success.close()
file_output.write("success: "+str(host_name+"\n"))
file_output.close()
# printing output if required from remote machine
#stdin,stdout,stderr = ssh.exec_command("hostname&&uptime")
#for line in stdout.readlines():
# print (line.strip())
except paramiko.SSHException:
# print ("error")
file_failed.write(str(host_name+"\n"))
file_failed.close()
file_output.write("failed: "+str(host_name+"\n"))
file_output.close()
#quit()
except paramiko.ssh_exception.NoValidConnectionsError:
#print ("might be windows------------")
file_output.write("failed: " + str(host_name + "\n"))
file_output.close()
file_failed.write(str(host_name+"\n"))
file_failed.close()
#quit()
except socket.gaierror:
#print ("wrong hostname/dns************")
file_output.write("error: "+str(host_name+"\n"))
file_output.close()
file_error.write(str(host_name + "\n"))
file_error.close()
ssh.close()
def performer1():
while True:
hostname_value = q.get()
check_hostname(hostname_value,pw_sent)
q.task_done()
if __name__ == '__main__':
print ("This script checks all the hostnames in the input_file with your standard password and write the outputs in below files: \n1.file_output\n2.file_success \n3.file_failed \n4.file_error \n")
f = open('output_file', 'w')
f.write("-------Output of all hosts-------\n")
f.close()
f = open('success_file', 'w')
f.write("-------Success hosts-------\n")
f.close()
f = open('failed_file', 'w')
f.write("-------Failed hosts-------\n")
f.close()
f = open('error_file', 'w')
f.write("-------Hosts with error-------\n")
f.close()
with open("input_file") as f:
hostname1 = f.read().splitlines()
#Read the standard password from the user
pw_sent=getpass.getpass("Enter the Password:")
for i in hostname1:
q.put(i)
#print ("all the hostname : "+str(list(q.queue)))
for no_of_threads in range(3):
t = threading.Thread(target=performer1)
t.daemon=True
t.start()
q.join()
print ("Check output files for results")
print ("completed task in" + str(time.time()-start_time1) + "seconds")

Finding PID's of Virtual Machine in openstack

I am working on openstack and I want to monitor the Virtual Machines cpu usage. For that I want to find their PIDs through the parent (central) openstack instance.
I used
ps aux | grep
and I did receive an output. I however want to confirm if this is correct PID. Is their any way I can check this?
Or is their any other way to find the PID's of the virtual machine?
Update.
This command does not work . It gives me a PID which always change. Its not constant.
Thank you
Well libvirt has some interfaces for this. Here's some python that extracts that data into datastructures for you:
#!/usr/bin/env python
# Modules
import subprocess
import traceback
import commands
import signal
import time
import sys
import re
import os
import getopt
import pprint
try:
import libvirt
except:
print "no libvirt detected"
sys.exit(0)
from xml.dom.minidom import parseString
global instances
global virt_conn
global tick
global virt_exist
def virtstats():
global virt_exist
global virt_conn
global instances
cpu_stats = []
if virt_exist == True:
if virt_conn == None:
print 'Failed to open connection to the hypervisor'
virt_exist = False
if virt_exist == True:
virt_info = virt_conn.getInfo()
for x in range(0, virt_info[2]):
cpu_stats.append(virt_conn.getCPUStats(x,0))
virt_capabilities = virt_conn.getCapabilities()
domcpustats = 0
# domcpustats = virDomain::GetcpuSTATS()
totmem = 0
totvcpu = 0
totcount = 0
vcpu_stats = []
for id in virt_conn.listDomainsID():
dom = virt_conn.lookupByID(id)
totvcpu += dom.maxVcpus()
vcpu_stats.append(dom.vcpus())
totmem += dom.maxMemory()
totcount += 1
dom = parseString(virt_capabilities)
xmlTag = dom.getElementsByTagName('model')[0].toxml()
xmlData=xmlTag.replace('<model>','').replace('</model>','')
for info in virt_info:
print info
for stat in cpu_stats:
print "cpu %s" % stat
for vstat in vcpu_stats:
print "vcpu:\n"
pprint.pprint(vstat)
print "CPU ( %s ) Use - %s vCPUS ( %s logical processors )" % (xmlData, totvcpu, virt_info[2])
sys.exit(0)
def main():
try:
global virt_conn
global virt_exist
virt_conn = libvirt.openReadOnly(None)
virt_exist = True
except:
virt_exist = False
print "OK: not a compute node"
sys.exit(0)
virtstats()
if __name__ == "__main__":
main()
Now what you get from this in terms of usage is cpu time.
The vcpu blocks are basically in this layout:
1st: vCPU number, starting from 0.
2nd: vCPU state.
0: offline
1: running
2: blocked on resource
3rd: CPU time used in nanoseconds
4th: real CPU number
The CPU blocks are obvious once you realize that's what's goin down in libvirt.
Hope that helps!
By using libvirt, python, lxml, and lsof you can recover the pid if your Virtual Instance (domain) has a display output set. (VNC, Spice, ...)
Retrieve display port
Retrieve pid from opened display port
Here is the code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from lxml import etree
import libvirt
from subprocess import check_output
def get_port_from_XML(xml_desc):
tree = etree.fromstring(xml_desc)
ports = tree.xpath('//graphics/#port')
if len(ports):
return ports[0]
return None
def get_pid_from_listen_port(port):
if port is None:
return ''
return check_output(['lsof', '-i:%s' % port, '-t']).replace('\n','')
conn = libvirt.openReadOnly('')
if conn is None:
print 'Failed to open connection to the hypervisor'
sys.exit(1)
for domain_id in conn.listDomainsID():
domain_instance = conn.lookupByID(domain_id)
name = domain_instance.name()
xml_desc = domain_instance.XMLDesc(0)
port = get_port_from_XML(xml_desc)
pid = get_pid_from_listen_port(port)
print '%s (port:%s) (pid:%s)' % (name, port, pid)
grep "79d87652-8c8e-4afa-8c13-32fbcbf98e76" --include=libvirt.xml /path/to/nova/instances -r -A 2 | grep "<name" | cut -d " " -f 3
allows to find "instance-" which can be mapped to ps aux output of "-name" parameter. so you can map openstack instance id to pid.
The most simple way is using cgroups:
In Ubuntu:
cat /sys/fs/cgroup/cpuset/libvirt/qemu/<machine-name>/tasks

Using pytest with Jython

I'm trying to use pytest on Jython. And I'm getting stuck right at the beginning.
I've successfully installed the pytest package with easy_install:
$ ./jython easy_install pytest
When I try to run example from this page, things go wrong. I receive an extremely long failure report, like the one bellow. Does anybody have any idea why this is happening?
py.test-jython
============================= test session starts ==============================
platform java1.6.0_37 -- Python 2.5.3 -- pytest-2.3.2
collected 1 items
test_sample.py F
=================================== FAILURES ===================================
_________________ test_answer __________________
def test_answer():
assert func(3) == 5
test_sample.py:5:
self = AssertionError()
def __init__(self, *args):
BuiltinAssertionError.__init__(self, *args)
if args:
try:
self.msg = str(args[0])
except py.builtin._sysex:
raise
except:
self.msg = "<[broken __repr__] %s at %0xd>" %(
args[0].__class__, id(args[0]))
else:
f = py.code.Frame(sys._getframe(1))
try:
source = f.code.fullsource
if source is not None:
try:
source = source.getstatement(f.lineno, assertion=True)
except IndexError:
source = None
else:
source = str(source.deindent()).strip()
except py.error.ENOENT:
source = None
# this can also occur during reinterpretation, when the
# co_filename is set to "<run>".
if source:
self.msg = reinterpret(source, f, should_fail=True)
../jython2.5.3/Lib/site-packages/pytest-2.3.2-py2.5.egg/_pytest/assertion/reinterpret.py:32:
source = 'assert func(3) == 5', frame =
should_fail = True
def interpret(source, frame, should_fail=False):
mod = ast.parse(source)
visitor = DebugInterpreter(frame)
try:
visitor.visit(mod)
../jython2.5.3/Lib/site-packages/pytest-2.3.2-py2.5.egg/_pytest/assertion/newinterpret.py:49:
.
.
.
self = <_pytest.assertion.newinterpret.DebugInterpreter object at 0x4>
name = Name
def visit_Name(self, name):
explanation, result = self.generic_visit(name)
../jython2.5.3/Lib/site-packages/pytest-2.3.2-py2.5.egg/_pytest/assertion/newinterpret.py:147:
self = <_pytest.assertion.newinterpret.DebugInterpreter object at 0x4>
node = Name
def generic_visit(self, node):
# Fallback when we don't have a special implementation.
if _is_ast_expr(node):
mod = ast.Expression(node)
co = self._compile(mod)
try:
result = self.frame.eval(co)
except Exception:
raise Failure()
explanation = self.frame.repr(result)
return explanation, result
elif _is_ast_stmt(node):
mod = ast.Module([node])
co = self._compile(mod, "exec")
try:
self.frame.exec_(co)
except Exception:
raise Failure()
return None, None
else:
raise AssertionError("can't handle %s" %(node,))
E AssertionError: can't handle Name
../jython2.5.3/Lib/site-packages/pytest-2.3.2-py2.5.egg/_pytest/assertion/newinterpret.py:134: AssertionError
=========================== 1 failed in 0.55 seconds ===========================
Pytest has a workaround for jython's lacking AST implementation, see issue1479. I just extended the workaround on the pytest side to work on jython-2.5.3. You can install a dev-candidate of pytest with:
pip install -i http://pypi.testrun.org -U pytest
and should get at least version 2.3.4.dev1 with "py.test-jython --version" and get assertions working with jython-2.5.3.
Currently pytest does not support Jython2.5.3, works only on Jython2.5.1.