How I can save the output in a text file - python

I use the library TextRazor to analyze a text and save it in a text file but when I open the file it's empty
import os
textrazor.api_key = ""
client = textrazor.TextRazor(extractors=["word","entities", "topics","sentence","words"])
response = client.analyze("Twenty-four isolates (60%) were associated with pneumonia, 14 (35%) with upper respiratory tract infections, and 2 (5%) with bronchiolitis. Cough (82.5%), fever (75%), and malaise (58.8%) ")
for entity in response.entities():
print(entity.id, entity.relevance_score, entity.confidence_score, entity.freebase_types)
cmd = os.popen('ls -w').read() # Récupération de la sortie de ls -a dans la variable cmd
print(cmd) # Affichage de la sortie
with open('monfichier.txt', 'w') as file:
s=str(cmd)
file.write(s)

ls -w is not a valid command as an integer is needed after the -w. Furthermore, do not use os.popen: it is not portable. Use the Python API instead (see os.walk).

Related

Problem with cryptography.fernet: decrypt my code with a wrong key

I was working with fernet to encrypt. In the tests I founded that if I change the last character of the key, fernet it is able to dencrypt.
For example if the key is ZwvCXUGvnG0RvkhNszIQsQOqz8yaKjUSJpxraDVsxd4= and i type ZwvCXUGvnG0RvkhNszIQsQOqz8yaKjUSJpxraDVsxd5= instead, the program dencrypt my code. I founded this error bc i was lazy to copy a whole new key, so i decided to only change the last character. This happen with every consecuent character in the last one character of the key.
If anyone could help me i would be very thankfull
This is my code
from cryptography.fernet import Fernet
text1="""Find me and follow me through corridors, refectories and files
You must follow, leave this academic factory
You'll find me in the matinée, the dark of the matinée
It's better in the matinée, the dark of the matinée is mine
Yes, it's mine"""
def crearLLave():
key=Fernet.generate_key()
print(key.decode())
return Fernet(key)
def crearLLaveManual(llave):
try:
return Fernet(llave)
except:
again=bytes(input("Formato incorrecto "), "ascii")
return crearLLaveManual(again)
def encriptarTexto(cadena, llave):
return llave.encrypt(str.encode(cadena))
def desencriptarTexto(cadena_encriptada, llave):
try:
return llave.decrypt(cadena_encriptada).decode()
except:
cadena=bytes(input("La cámara de los secretos no se abrirá, intente de nuevo: "),"ascii")
return desencriptarTexto(cadena_encriptada, crearLLaveManual(cadena))
llave=crearLLave()
texto_encriptado=encriptarTexto(text1, llave)
print("La cadena encriptada es: ",texto_encriptado.decode())
cadenaLlave=bytes(input("Escriba la llave para desencriptar el texto: "), "ascii")
llaveManual=crearLLaveManual(cadenaLlave)
print("El texto desencriptado es: ",desencriptarTexto(texto_encriptado, llaveManual))
Console Message:
lIX2AfP-cyFRNgYgFRf3Sy3uKQ4Hrr4Lvrn12wFGo30=
La cadena encriptada es: gAAAAABjg7kdWTCIRjIrIAFk2fQg-znc1zRdrc7VaTkjcKZL1RZ2jmCjvf6NlzQ-39yxh0BMXY0FkrBTN0Ky51HiGy9cxmlbpZ7_Jwp6wml2DsMkCWf7h49EYLN8hjtpzFoiTUy7coguSXgFDBVVyucAUhgcn1EzleHJ_pKlDsyw6EnNLVBqUkmI8WYOY5NwEfCKx3UUlvV3dYDZqjeVqMX90CaAueUMtgDvcVP77tkngK7U2jfneH85bxBo8LJooenFnVeqNxwc70a8vY-GmOihnbDyAOT-GYwmLMssMP5QYDWNBnnTEmMSm4Dt-OHCvOYRyie82T6Art6PK5miinVsjsvkXpd6g343tmNSg34XMbMqgTIILXB7t6gZqdfnpUNUJ6vLfQvM4s4bYSltEEgTSIwrMUUUbA==
Escriba la llave para desencriptar el texto: lIX2AfP-cyFRNgYgFRf3Sy3uKQ4Hrr4Lvrn12wFGo31=
El texto desencriptado es: Find me and follow me through corridors, refectories and files
You must follow, leave this academic factory
You'll find me in the matinée, the dark of the matinée
It's better in the matinée, the dark of the matinée is mine
Yes, it's mine

What do I wrong to send json data to stock it on server by php from a local python app?

So, my problem is :
I have a file (data_test.json) on the web. I wrote and uploaded it myself.
{
"a" : 1,
"b" : 42,
"c" : 3.14
}
My local python code in Renpy read it rightly.
init python:
def get_stats():
# Déclaration des variables
global test_a
global test_b
global test_c
# Importation des modules
import requests
import json
# Atteindre le fichier
r = requests.get("https://lecot-christophe.com/rpu_json/data_test.json")
# Aquérir les données sous forme de texte
r.text
# Convertir en dictionnaire Python
var = json.loads(r.text)
# Boucler pour extraire et distribuer les résultats à travers les variables
for i in var:
test_a = var['a']
test_b = var['b']
test_c = var['c']
Then the python code makes an update. I think python send rightly the data cause of the response of the requests. post is positive.
def post_stats(file):
global test_a
global test_b
global test_c
global send_test
import requests
import json
url = "https://*monsite*/rpu_json/renpy_json_manager.php"
# Composition des données
file_name = file+".json"
aDict = {
"a":test_a,
"b":test_b,
"c":test_c
}
json_object = json.dumps(aDict)
# Adresser le fichier
data_test = requests.post(url, json=json_object)
send_test = data_test.status_code
PHP receive the posted data or not, and update the json file.
<?php
$json = $_POST['data'];
$info = json_encode($json);
$file = fopen('data_test.json','w+') or die("File not found");
fwrite($file, $info);
fclose($file);
?>
But the content of data-test.json is now just "null".
null
So... Where did I make a big mistake ?

Launching Python script including Paho-mqtt library in RPi rc.local

I have installed Paho-mqtt python libray by "pip3 install paho-mqtt" on my RPi which I use for home automation purposes.
I made a python script to regulate my heatpump.
My script:
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Programme de régulation de température
"""
import time
import json
import requests
from requests.auth import HTTPBasicAuth
import paho.mqtt.subscribe as subscribe
import paho.mqtt.publish as publish
#***********Récupération de l'état d'un élément de Domoticz***********
def dom_elmt(idx, valeur):
url= 'http://127.0.0.1/json.htm?type=devices&rid='
adresse= url+idx
r=requests.get(adresse)
status=r.status_code
if status == 200:
# l'API renvoie 200 si tout est OK
getinfos=r.json()
for i, v in enumerate(getinfos["result"]):
#Récupération de la donnée "Status" du switch
result= getinfos["result"][i][valeur]
return result
#***********FIN Récupération de l'état du clavier************
#***********
Prev_Setpoint = 0
while True:
msg = subscribe.simple("zigbee2mqtt/Thermo-Hygro Salle", hostname="127.0.0.1")
y = json.loads(msg.payload)
Temp = y["temperature"]
print(time.strftime('%H:%M:%S', time.localtime()) ,"Température salle : ",Temp)
#******** lecture du point de consigne idx: 230 ************
Consigne=dom_elmt('230', "SetPoint")
Consigne=float(Consigne)
if Temp > Consigne + 0.2:
Setpoint = Consigne - 0.5
if Temp >= Consigne - 0.2 and Temp <= Consigne + 0.2:
Setpoint = Consigne
if Temp < Consigne - 0.2:
Setpoint = Consigne + 0.5
Setpoint = str(Setpoint) # Transformation d'un float en str
if Setpoint != Prev_Setpoint: # Le point de consigne calculé est différent du précédent
a = "{"
b = '"temperature"'
c = ":"
d = "}"
sendtemp = a+b+c+Setpoint+d
publish.single("heatpump/set", sendtemp, hostname="127.0.0.1")
Prev_Setpoint = Setpoint # Mise à jour de Prev_Setpoint
If I launch this script on a console it works perfectly. I need but I can't launch it at boot in the rc.local.
....
if [ "$_IP" ]; then
printf "My IP address is %s\n" "$_IP"
fi
python /home/pi/thermostat.py &
exit 0
This don't work and I don't understand what happen ?! (I launched other scripts in rc.local whithout any problem)
Does someone has an idea to help me ???
Thanks in advancecd
This is because the python script will get killed when the script that started it exits even if it is pushed to the background with &.
The hacky solution is to prefix the command with nohup (which means the process will not get sent the Hang Up signal when the parent script exits).
The better option would be to write a proper systemd service definition for your script.

when converting python to exe : code signature invalid for

so I have a simple code that create a graphical interface with Tkinter on python, but when I convert it to exe using PyInstaller I get this issue , I don't understand what's happening
Error loading Python lib '/Users/salwafakhir/dist/app/Python': dlopen: dlopen(/Users/salwafakhir/dist/app/Python, 10): no suitable image found. Did find:
/Users/salwafakhir/dist/app/Python: code signature invalid for '/Users/salwafakhir/dist/app/Python'
here is a part of the code
creer une premiere fenetre
masterWindow= Tk()
#personnaliser ma fenetre
masterWindow.title("logistics interface")
masterWindow.geometry("1280x1024")
masterWindow.minsize(480 , 360)
masterWindow.config(background='white')
#creer frame
frameProduct_1W=Frame(masterWindow,bg='white')
image = PhotoImage(file="/Users/salwafakhir/Desktop/seaver-sangle-connecte-equitation-technologie.png")
label = Label(image=image)
label.pack(expand=YES)
#ajouter un premier texte
Label_title =Label(frameProduct_1W,text="Welcome to SeaverLogictec",font=("Time New Roman",40),bg='white', fg="#3A67C1").pack(expand=YES)
ajouter un second texte
Label_subtitle =Label(frameProduct_1W,text="We are here to help you with Stock management and order placing ",font=("Time New Roman",15),bg='white', fg="#3A67C1").pack(expand=YES)
#connection a la base de donne logistic
conn = MongoClient()
db = conn.admin
#ajouter un premier bouton
startButton= Button(frameProduct_1W,text="Let's get started",font=("Time New Roman",40),bg='white', fg='#3A67C1', command=open).pack(expand=YES)
#ajouter frameProduct_1W
frameProduct_1W.pack(expand=YES)
#afficher
masterWindow.mainloop()

Writing in another file in python leaves my file empty

def enr_score(nom_jouer, n, con):
score = open('Score.txt', 'a')
seconds = time.time()
local_time = time.ctime(seconds)
score.write("Temp de registration: ")
score.write(local_time)
score.write("JOUER: ")
score.write(nom_jouer)
score.write("\n")
score.write("Il/Elle a fini le jeu avec - ")
score.write(n)
score.write(" - disques apres - ")
score.write(con)
score.write(" - tentatives.")
score.write("\n")
score.close()
return "Ton score a ete enregistre!"
I got this code but for some reason when I check the Score.txt file it's empty. Shouldn't something be written in it?
There's no errors btw
This is the code that calls the function btw
nom_jouer = input("\nComment vous appelez vous? \n \nUSERNAME: ") #demande le nom de jouer
from Partie_E import enr_score
nr_disq = str(n)
tent = str(con)
enr_score(nom_jouer, nr_disq, tent)
Ok. So, basically I was a bit dumb (I'm relatively new to programming) and didn't realize I was editing another file than the one I was looking at.
It created the file in an outside folder and I thought it would edit the already existing one in the same folder as the .py files.
Sorry for the mind-F.

Categories