Comparing utf decoded value with a string value
I have been trying to compare the UTF-decoded data from pyserial
with a value of a similar data type. However, it never returns true.
Please refer to the Python 3 code below:
import serial.tools.list_ports
import serial
serialInst = serial.Serial()
serialInst.bandrate = 9600
serialInst.port = portvar
serialInst.open()
while True:
if serialInst.in_waiting:
packet = serialInst.readline()
num = packet.decode("utf")
print("num is: ")
print(num) # prints 0
print(type(num)) # returns <class 'str'>
print(num == '0') # returns false
do you know?
how many words do you know
See also questions close to this topic
-
Python File Tagging System does not retrieve nested dictionaries in dictionary
I am building a file tagging system using Python. The idea is simple. Given a directory of files (and files within subdirectories), I want to filter them out using a filter input and tag those files with a word or a phrase.
If I got the following contents in my current directory:
data/ budget.xls world_building_budget.txt a.txt b.exe hello_world.dat world_builder.spec
and I execute the following command in the shell:
py -3 tag_tool.py -filter=world -tag="World-Building Tool"
My output will be:
These files were tagged with "World-Building Tool": data/ world_building_budget.txt hello_world.dat world_builder.spec
My current output isn't exactly like this but basically, I am converting all files and files within subdirectories into a single dictionary like this:
def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree
Right now, my dictionary looks like this:
key:''
.In the following function, I am turning the empty values
''
into empty lists (to hold my tags):def empty_str_to_list(d): for k,v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v)
When I run my entire code, this is my output:
hello_world.dat ['World-Building Tool'] world_builder.spec ['World-Building Tool']
But it does not see
data/world_building_budget.txt
. This is the full dictionary:{'data': {'world_building_budget.txt': []}, 'a.txt': [], 'hello_world.dat': [], 'b.exe': [], 'world_builder.spec': []}
This is my full code:
import os, argparse def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree def empty_str_to_list(d): for k, v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v) parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--filter", action="store", help="keyword to filter files") parser.add_argument("--tag", action="store", help="a tag phrase to attach to a file") parser.add_argument("--get_tagged", action="store", help="retrieve files matching an existing tag") args = parser.parse_args() filter = args.filter tag = args.tag get_tagged = args.get_tagged current_dir = os.getcwd() files_dict = fs_tree_to_dict(current_dir) empty_str_to_list(files_dict) for k, v in files_dict.items(): if filter in k: if v == []: v.append(tag) print(k, v) elif isinstance(v, dict): empty_str_to_list(v) if get_tagged in v: print(k, v)
-
Actaully i am working on a project and in it, it is showing no module name pip_internal plz help me for the same. I am using pycharm(conda interpreter
File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\Scripts\pip.exe\__main__.py", line 4, in <module> File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_internal\__init__.py", line 4, in <module> from pip_internal.utils import _log
I am using pycharm with conda interpreter.
-
Looping the function if the input is not string
I'm new to python (first of all) I have a homework to do a function about checking if an item exists in a dictionary or not.
inventory = {"apple" : 50, "orange" : 50, "pineapple" : 70, "strawberry" : 30} def check_item(): x = input("Enter the fruit's name: ") if not x.isalpha(): print("Error! You need to type the name of the fruit") elif x in inventory: print("Fruit found:", x) print("Inventory available:", inventory[x],"KG") else: print("Fruit not found") check_item()
I want the function to loop again only if the input written is not string. I've tried to type return Under print("Error! You need to type the name of the fruit") but didn't work. Help
-
Reverse words in a string in C++
Can anyone please tell that why the below written code isnt working , theres no error but its simply printing the string which was passed and is not reversing it.
Logic: First reverse individual words and after reversing all the words in a string simply reverse the entire string.
I/P : hello world O/P : world hello
Below is the code:
#include <bits/stdc++.h> using namespace std; void reverse(string str,int low, int high){ while(low<=high){ swap(str[low],str[high]); low++; high--; } } void reverseWords(string str){ int start=0; int n = str.length(); for(int end=0;end<n;end++){ if(str[end]==' '){ reverse(str,start,end-1); start=end+1; } } reverse(str,start,n-1); reverse(str,0,n-1); cout<<str; } int main() { string s = "Welcome to Gfg"; cout<<"After reversing words in the string:"<<endl; reverseWords(s); return 0; }
-
Modify user input to use in exec call
I am trying to modify a user input string to call execvp in a future function. In my code I have a function which tokenises the user input such that if the user entered in: command a b c. It outputs
char** output = { "command", "a", "b", "c", NULL }
The length of the user input is unknown. My issue is that I want to modify the variable char** output to remove the user entered command, such that I getchar** output = {"a", "b", "c", NULL }
My current attempt at this is in the code below:char** exec_arg(char** output, int numTokens){ 143 char* argExec[numTokens]; 147 for(int k = 0; k < (numTokens-1); k++){ 148 argExec[k] = output[k+1]; 149 printf("%s", argExec[k]); 150 } 152 return argExec; 155 }
However I am finding that when I run this I am getting the output: {"a", "b", "c"}
- create string r using string p and q, C++, Data Structures, Strings
-
Can't read serial response using pyserial
Trying to use pyserial to talk to a Korad KD3005P power supply. (Using Python 3.6)
import serial ser = serial.Serial('/dev/ttyACM0', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=1) ser.write(b'VSET1:2') ser.write(b'VOUT1?') response = ser.readline() print(response)
VSET1:2
sets the voltage to 2 voltsVOUT1?
tells the device to return the current voltage.But all I get from the
VOUT1?
part seems to be:b''
Stuff I've checked or tried without success:
- The device works - I can talk to the device and get responses successfully with these commands through a serial terminal like CuteCom
- Pyserial is kinda working - if I run the above program, the
VSET1:2
does change the voltage. - I've tried different timeouts
- I've tried
ser.read()
instead with various bit lengths - I've tried putting the read commands in a while loop
Any suggestions?
-
Using pyautogui.write to create a new name each time
Newbie over here so apologies in advance for any poor syntax/phrasing of the question.
I am attempting to automate some of my test equipment that does not play nicely with standard serial port streaming of data. I'm using pyautogui to replicate many of my daily actions and its been awesome. **I have a 3rd party program that I have to export data from and I am looking for a way to use pyautogui.write to be able to write slightly next text each time e.g. "Test 1a -> Test 1b
-
pyserial read qr code and take action on arduino
I'm reading qr code using opencv and pyzbar, i'm communicating with an arduino uno using pyserial.
my python code
from pyzbar.pyzbar import decode import cv2 import serial import time arduino = serial.Serial(port='COM6', baudrate=115200, timeout=1) def write_read(x): arduino.write(bytes(x, 'utf-8')) time.sleep(0.05) data = arduino.readline() return data cap = cv2.VideoCapture(0) def get_qr_data(input_frame): try: return decode(input_frame) except: return [] while True: _, frame = cap.read() qr_obj = get_qr_data(frame) cv2.imshow("DD", frame) print(qr_obj) # cv2.imshow("DD2", frame2) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
from
qr_obj = get_qr_data(frame)
i get the result[Decoded(data='asd', type='QRCODE', rect=Rect(left=115, top=155, width=225, height=223), polygon=[Point(x=115, y=378), Point(x=340, y=370), Point(x=335, y=155), Point(x=119, y=155)], quality=1, orientation='UP')]
im trying to print the qr data in arduino serial monitor and turn on the arduino built in led
my arduino code
char x; void setup() { Serial.begin(115200); Serial.setTimeout(1); pinMode(LED_BUILTIN, OUTPUT); } void loop() { while (!Serial.available()); x = Serial.read(); Serial.println(x); if(Serial.read() == x) { digitalWrite(LED_BUILTIN, HIGH); } }
The built in led doesn't turn on and nothing is written in the serial monitor
-
Create a single character that changes to a different emoji rapidly
I've spent all day just trying to figure out how to phrase this, so please help me if I need to edit the post.
I'm trying to create some text in c# that I want to output in the console, but I want that text to be emojis (✊, ✌️, 🖐), but to replace each other every few miliseconds in a single character, if that makes sense. I've gotten help and managed to create that effect with plain text:
string first = "ABC"; for (int i = 0; i < 20; i++) { Console.Write(first[i % 3] + "\r"); Thread.Sleep(100); } Console.WriteLine("\n");
Then I tried to replace those characters with some unicode "codes" \uD83D\uDC4A (don't know what to call them). I then ran the program, and the output in the console was just "�". I really don't know how to phrase this post, so please feel free to suggest edits and ask questions about it
-
Converting mlflow binary model file into text file
I've just lost all my repositories where I stored scripts of my models which was uploaded into mlflow. I always load my models into mlflow via python api and jupyter where I load model as python class. All my models still working perfectly in mlflow but I cannot find scripts of my class in mlflow repository. I guess that script of uploaded model is stored as binary file which is available in model directory as other artifacts which were uploaded. Unfortunately, I cannot open this file and convert this into utf-8 to be able read it as jupyter file. Anyone has some idea how can I restore script of my uploaded model class to readable version from mlflow binary model file?