Split a list of results from devcon in python - python

I'm writing a python script where I'm trying to gather a list device connected via USB with the goal of removing the USB ports so I can readd them guaranteeing a specific cable is COM3. I have a batch file that does this, however I need to add more functionality than the batch file can handle.
list = []
#This section finds all connected USB ports and works
ports = subprocess.run("devcon FindAll =ports", stdout=subprocess.PIPE).stdout.splitlines()
for x in ports:
list.append(x.decode('utf-8'))
#This section splits the results from above and places them in a list
print(list[0])
cmd_0 = str('devcon remove #\\" + list[0])
list2 = [cmd_0.split(" ", 1 [1] for item in list]
print(cmd_0)
when I run the code I get the following result:
**devcon remove #usb\ACPI\PNP0501\0** : Communications Port (COM1)
What I can't figure out is how to get rid of everything after the bold section.
Thanks in advance for the help.
I have tried various methods for splitting the cmd_0 output but can't find the correct method.

Related

Find IP address which occurs most frequent and count the number of times that it appears

Hi all First time having to look for assistance but i am sort of at a brick wall for now. i have been learning python since August and i have been giving a challenge to complete for the end of Novemeber and i hope that there could be some help in making my code works. My task requires to find an ip address which occurs most frequent and count the number of times it appears also this information must be displayed to the user i have been giving 4 files .txt that have the ips. I am also required to make use of non trivial data structures and built in python sorting and/or searching functionalities, make use of functions, parameter passing and return values in the program. Below is a sample data structure they have recommended that i use: -
`enter code here`
def analyse_logs(parameter):
# Your Code Hear
return something
def extract_ip(parameter):
# Your Code Hear
return something
def find_most_frequent(parameter):
# Your Code Hear
return something
# Test Program
def main():
# Your Code Hear
# Call Test Program
main()
And below hear is what i have came up with and the code is completley differant from the sample that has been provided but what i have done dosnt give me output straight back instead creats a new text file which has been sorted but now what i am looking for: -
enter code here
def sorting(filename):
infile = open(filename)
ip_addr = []
for line in infile:
temp = line.split()
for i in temp:
ip_addr.append(i)
infile.close()
ip_addr.sort()
outfile = open("result.txt", "w")
for i in ip_addr:
outfile.writelines(i)
outfile.writelines(" ")
outfile.close()
sorting("sample_log_1.txt")e here
The code that i have created has sorted everything thats in the .txt file and outputs the most frequent that has been used all the way to the lest frequent. All i am look for is for an algorithim that can sort through the .txt file, find the IP address thats more frequent then print that ip out and how many times it appears. I hope i have provided everything and i am sure this is probally somthing very basic but i just cant get my head round it.
You should keep the number of times the IP addresses are repeated in a variable. You can use dictionary.
ip_count_dict = {"IP1": repeat_count, "IP2": repeat_count}
When first time you find a IP in your list set repeat_count 1 and after that if you find same ip again just increase counter.
For example,
ip_count_dict = {}
ip_list = ['1.1.1.1','1.1.1.2','1.1.1.3','1.1.1.1']
#Loop and count ips
#Final version of ip_count_dict {'1.1.1.1':2 , '1.1.1.2':1, '1.1.1.3':1}
With this dictionary you can store all ips and sort by their value.
P.S.: Dictionary keeps key,value pairs you can search "sort dictionary by value" after all counting thing done.

How to get only COMx in Serial.Tools.List (Python)?

I created a program, which sorts all connected Devices (Serials). I only want the List to get COMx Ports instead of their description.
import serial.tools.list_ports
ports = serial.tools.list_ports.comports()
List1 = []
for port in sorted(ports):
List1.append(port)
print(*List1)
It always shows the description too, and i don't know what to do?
Can anyone help me to solve this problem? Any Ideas?
I also read the pyserial documentation and tried to divide results into port, desc, hwid, didn't work...
If you are on Windows, you will be able to list only the COM port names with one of the following:
List1.append(port.name)
or
List1.append(port.device)
If you stick to the string named COMx, you can change comports() to:
ports = serial.tools.list_ports.grep("COM[1-9][0-9]*")
serial.tools.list_ports
classserial.tools.list_ports.ListPortInfo
device
Full device name/path, e.g. /dev/ttyUSB0. This is also the information returned as first element when accessed by index.
name
Short device name, e.g. ttyUSB0.

Python compare two lists of IPs and return the lowest to 0 IP entry in list?

I have managed to compile two lists of IP addresses. used and unused ips as such
unused_ips = ['172.16.100.0/32', '172.16.100.1/32', '172.16.100.2/32', '172.16.100.3/32', '172.16.100.4/32', '172.16.100.5/32', '172.16.100.6/32', '172.16.100.7/32', '172.16.100.8/32', '172.16.100.9/32'...]
used_ips = ['172.16.100.1/32','172.16.100.33/32']
what I want to be able to do now is compare these lists and return the next free IP. in the above example the next ip would be 172.16.100.2/32, until it handed out all of those from 1 to 32 then it would hand out 34.
im not sure where to begin with this, I can convert these to IPv4Network objects if there is something built in for this but I couldn't find anything in documentation
Thanks
I'd keep a set of ipaddress objects and manipulate them to allocate and de-allocate the addresses, like so:
import ipaddress
def massage_ip_lists():
global unused_ips, used_ips
unused_ips = set(ipaddress.ip_address(ip.replace('/32', ''))
for ip in unused_ips)
used_ips = set(ipaddress.ip_address(ip.replace('/32', ''))
for ip in used_ips)
def allocate_next_ip():
new_ip = min(unused_ips - used_ips)
used_ips.add(new_ip)
return new_ip
unused_ips = [
'172.16.100.0/32',
'172.16.100.1/32',
'172.16.100.2/32',
'172.16.100.3/32',
'172.16.100.4/32',
'172.16.100.5/32',
'172.16.100.6/32',
'172.16.100.7/32',
'172.16.100.8/32',
'172.16.100.9/32']
used_ips = ['172.16.100.1/32', '172.16.100.33/32']
massage_ip_lists()
print(allocate_next_ip())
print(allocate_next_ip())
Note:
/32 is a nomenclature for IP networks, not IP hosts.
ipaddress objects are comparable, so functions like min() work on them.
172.16.100.0 is a perfectly valid IP address, depending upon the netmask. If you don't want to allocate it, either keep it out of unused_ips, or make the program aware of the netmask in use.
You want ips that are in unused but not used:
available_ips = [ip for ip in unused_ips if ip not in used_ips]
You want to sort them to get the one that's closest to zero. Naive sorting will not work as you have strings; 172.16.xxx.xxx is sorted higher than 172.100.xxx.xxx for example. You can convert the IPs into lists of numbers to sort them correctly.
import re
available_ips = sorted(available_ips, key=lambda ip: (int(n) for n in re.split(r'[./]', ip)))
If you're just trying to iterate through a list of the available ips, you could do something like this:
# Filter unavailable ips from the list of all ips
available_ips = set(unused_ips) - set(used_ips)
# Iterate through list of available ips
for ip in available_ips:
print(ip) # Or whatever you want to do with the next available ip

Printing in Duplexpage a word document

I am trying to automate the task of printing two copies at double page of ~30 Word document (*.doc). I want to send the program converted to .exe (I plan it just for Windows computers) using py2exe. I know that I can manually check the options but I will not be able to do so on the 20 or so computer where it will be used, as well as I cannot install in this computers new software (That's why I want to convert it into .exe).
I copied this solution to print, but I can't adapt it to do what I want:
from win32com import client
import time
word = client.Dispatch("Word.Application")
filename=input("What files do you want to print?")
def printWordDocument(filename):
"""Given a name of a file prints it. TODO: Add double page."""
word.Documents.Open(filename)
word.ActiveDocument.PrintOut()
time.sleep(2)
word.ActiveDocument.Close()
word.Quit()
I couldn't find any option to print in double pages, or at least automatically, the only option of double page of PrintOut method is ManualDuplexPrint which in the documentation says: "True to print a two-sided document on a printer without a duplex printing kit.", but I don't want to make it even easier to print all the set of documents. And make a program portable to other computers, without modifying the Word documents (I don't create them).
Any other way to do it? Or any other option to do it?
UPDATE
I am not able to code in visual-basic (yet), but if I get a template or some hints I think I will manage to make something adapted to my conditions.
I have ended doing a macro, but this just works for my own computer and not for all the computers where should work.
Sub Test()
'
' Test Macro
' Print in double page and 2 copies
'
ActivePrinter = "Xerox WC 24 PCL"
Application.PrintOut FileName:="", Range:=wdPrintAllDocument, Item:= _
wdPrintDocumentWithMarkup, Copies:=2, Pages:="", PageType:= _
wdPrintAllPages, Collate:=True, Background:=True, PrintToFile:=False, _
PrintZoomColumn:=0, PrintZoomRow:=0, PrintZoomPaperWidth:=0, _
PrintZoomPaperHeight:=0
End Sub

how can I grab video from usb video capture + dvb device with gstreamer?

I own a avermedia volar HX usb stick, I want to capture fromthe composite input , but I can't because I'm unable to select the input. I'm using gstreamer with + python, I think I need to use gsttuner select input but I have no experience using gstreamer's interfaces. Could someone post a simple example?
Thanks!
src = gst.element_factory_make("v4l2src", "src")
src.set_state(gst.STATE_PAUSED)
try:
# channel names will be different for each device
channels = src.list_channels()
composite = [x for x in channels if x.label == "Composite1"]
if composite:
self.src.set_channel(composite[0])
except AttributeError, e:
log.warn("Could not tune video source\n")
To anyone stumbling on this, some internal gstreamer changes since this was originally posted may require gst.STATE_READY now instead of STATE_PAUSED. Tripped me up as it seems half the capture devices I encounter default to PAL and I need to use the GST_TUNER interface to change it.
The code shown above seems basically correct, but it will flounder on the rocks of v4l2. The strings you get will depend on what card you have:
On four different cards so far I've encountered:
"Composite"
"Composite1"
"composite"
"Composite Video Input"
Also be aware that some cards will have the driver lie, since the chip set has four inputs, the driver will often report four, even if the manufacturer only connects to two of them.

Categories

Resources