Известна ли какая-либо проблема, из-за которой среда Python для Azure Runbook не поддерживает функцию цикла while в сочетании с функцией print без добавленияlush=True?
Я не видел ни одного оператора печати, возвращаемого, когда слово while было включено в основную функцию.
Это сделано для того, чтобы отправлять оповещения всякий раз, когда изменяется состояние моей виртуальной машины Azure. (Это будет по электронной почте, но для простоты я только что включил операторы печати... которые должны работать)
Удалите функцию while, и появятся все операторы печати. .
Это такая глупая ситуация. Даже print("Вы видите это сообщение...") и print("Ввод цикла...") не печатаются. Эти инструкции print даже не печатаются в цикле while, поэтому они должны печатать, даже если есть проблема с выполнением цикла while (чего нет). Я бы показал вам это с помощью отладочной печати, но если бы вещь действительно напечаталась так, как я сказал, вы бы это увидели.
Из-за этого у меня серьезно повышается кровяное давление. Compute_client аутентифицируется и возвращает правильное имя_VM, так почему же каждый раз, когда я включаю цикл while, он вызывает шипение?
Я так зол на это.
import time, random, smtplib, inspect, string
from datetime import datetime
from email.mime.text import MIMEText
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient
# Azure setup
subscription_id = 'xxx'
resource_group_name = 'xxx'
vm_name = 'xxx'
from azure.core.exceptions import ClientAuthenticationError
# Authentication of Azure's Service Principal
def service_principal_authentication():
"""Checks the Authentication of Azure's Service Principal """
print("Authenticating Service Principal....")
try:
credentials = ServicePrincipalCredentials(
client_id='xxx',
secret='xxx',
tenant='xxx'
)
print("Service Principal Authenticity Verified")
return ComputeManagementClient(credentials, subscription_id)
except Exception as e:
print(f"There was an error with the authenticating the Service Principal: {e}")
except ClientAuthenticationError as e:
print(f"Client Authentication Error {e}")
# Email setup
sender_email = 'xxx'
receiver_email = 'xxxx'
smtp_server = 'xxx'
smtp_port = 587
smtp_password = 'xxx'
def send_notification(subject, body):
"""Send an email notification."""
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = sender_email
msg['To'] = receiver_email
try:
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.login(sender_email, smtp_password)
server.sendmail(sender_email, receiver_email, msg.as_string())
print("Email sent successfully!")
except Exception as e:
print(f"{e} in ", inspect.stack()[0].function)
def get_vm_status(compute_client):
"""Retrieve the current status of the VM."""
print("Retrieving VM status......")
try:
# Explicitly request the instance view
vm = compute_client.virtual_machines.get(resource_group_name, vm_name, expand='instanceView')
# Check if instance view is available
if vm.instance_view:
print(f"Can you see this message? {inspect.stack()[0].function}")
return vm.instance_view.statuses[1].code # Assuming the status is at index 1
else:
print("Instance view is not available.")
return None
except ClientAuthenticationError as e:
print(f"There was a client authentication error {e}")
except Exception as e:
print(f"Error retrieving VM status: {e}, in function {inspect.stack()[0].function}")
def generate_incident_reference_number():
incident_timestamp = datetime.utcnow().strftime("%Y%m%d%H%M%S")
incident_number = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10))
return f"INC{incident_timestamp}{incident_number}"
def log_to_azure_monitor():
pass
def main():
print("Entering loop.....",flush=True)
while True:
compute_client = service_principal_authentication()
previous_vm_status = None
current_vm_status = get_vm_status(compute_client)
if current_vm_status != previous_vm_status:
incident_number = generate_incident_reference_number()
print(f"This has changed {current_vm_status} - {previous_vm_status} - {incident_number}", flush=True)
else:
print(f"This has remained the same {current_vm_status}", flush=True)
previous_vm_status = current_vm_status
time.sleep(10)
if __name__ == "__main__":
main()
Подробнее здесь: https://stackoverflow.com/questions/793 ... while-loop
Функция печати не работает без сброса = True при использовании с циклом While ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Функция печати не работает без сброса = True при использовании с циклом While
Anonymous » » в форуме Python - 0 Ответы
- 15 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Функция печати не работает без сброса = True при использовании с циклом While
Anonymous » » в форуме Python - 0 Ответы
- 15 Просмотры
-
Последнее сообщение Anonymous
-