#πŸ”’ Returning multiple values and calling them individually in another function

82 messages Β· Page 1 of 1 (latest)

warm linden
#

Hello everyone, question about returning multiple values from a function, and then parsing through that return and grabbing what I need in a different function, any tips or tricks. For reference, I'm returning 3 values, the first a IP address, the second the initial user response, and finally a false to end the while loop. Thanks in advance. def main():
while True:
u_response = input("NIC IP: 1\nBMC IP: 2\nExit: 3 ")
#basic user repsonse, to be checked.
if u_response.isdigit():
u_response = int(u_response)
match u_response:
case 1:
sys.stdout.write("Input IP: ")
sys.stdout.flush()
u_reply = sys.stdin.readline()
return u_reply, u_response, False
case 2:
sys.stdout.write("Input IP: ")
sys.stdout.flush()
u_reply = sys.stdin.readline()
return u_reply, u_response, False
case 3:
print("Thank you for using the script.")
return
case _:
print("Invalid response")

    else:
        print("Invalid response")    

#This will validate the ip / IPV4
def ip_validation():
pass

hybrid spadeBOT
#

@warm linden

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

empty wigeon
warm linden
#

Optimally yes, how would I unpack? New to more advanced concepts and trying to break into my se team from the hardware side

empty wigeon
#

!e ```py
def func():
return 'a', 'b', 'c'

result = func()
a = result[0]
b = result[1]
c = result[2]
print(a, b, c)```Are you trying to avoid this

hybrid spadeBOT
#

@empty wigeon :white_check_mark: Your 3.12 eval job has completed with return code 0.

a b c
warm linden
#

@empty wigeon No my only concern is the first return will be something like 102.246.2.14, will it keep that format>?

#

I need to check with socket if the ip address is actually valid and in the first portion I want to validate by pulling that first return

#

PS C:\Users\chris\Desktop\Version1> python -u "c:\Users\chris\Desktop\Version1\Version_one1.py"
NIC IP: 1
BMC IP: 2
Exit: 3 1
Input IP: 10.246.2.104
('u_reply', 'u_response', 'False')

empty wigeon
#

You want to check if the ip address matches the correct format for an ip address?

warm linden
#

Yeah so the intial func "main" just verifies the user selection, the intakes an ip address ipv4 to be exact. This func will then verify it is an actual address, then I'll pass that down to some ipmi commands to actually pull useful data for the debug tech

empty wigeon
#

You could use regex.

warm linden
#

Elaborate, I am mostly self-taught, if you wouldn't mind

empty wigeon
#

Provided for by the re module in Python.

#

It's a text pattern matching syntax.

tough breach
empty wigeon
#

You can ask it if text conforms to a given pattern, or to search through all instances of pattern matches in text.

tough breach
#

don't reinvent the wheel unless you really feel like doing it anyway

empty wigeon
#

Oh, okay, fair.

warm linden
#

oh nice, I was just using socket

#

IF_ANET to be exact

empty wigeon
tough breach
#

socket is useful for actually making network connections, ipaddress is more useful for parsing & validating actual address strings without making any connections
(it also supports ipv6 out of the box which would be much more annoying to implement manually)

empty wigeon
#

You're familiar with try and except, yeah?

warm linden
#

Yes

empty wigeon
#

Good good.

warm linden
#

I have a lot of the basics down, trying to incorporate bash in my python with subprocess because I work in a linux environment where the test server has direct access to all of the servers in test. Do you mind if I ask one more question?

empty wigeon
#

It's your party.

warm linden
#

Are you familiar with SOL connections and the like?

empty wigeon
#

I'm not database-y.

#

Oh, SOL.

warm linden
#

yeah haha

#

networking

empty wigeon
#

Sorry, my uselessness continues.

warm linden
#

But I want to run subproccess.Popopen([ipmi -I lanplus -U admin -P admin -H sol activate]), but I want to wait until the process has actually connected and got access to the local root host. Is there a built in function or something I could import for that?

#

This is what I do at work haha, I'm just trying to automate some of the work in hopes of transitioning into software.

#

And no your not useless, I appreciate the help

empty wigeon
warm linden
#

Thank you

#

Reading on regex now

empty wigeon
#

I think using the ipaddress module was a good suggestion.

warm linden
#

Yeah I'm using it now

empty wigeon
#

Regex is garbled sorcery that looks far more intimidating than it actually is, but it is very well-suited to its purpose.

#

If you can believe it, I've read of some cases where people have had regex patterns up to 100s of megabytes large.

warm linden
#

Oh my haha my use case is much less complex

empty wigeon
sage python
warm linden
#

Also I figured out a better solution to the code.

#

import subprocess
import sys
import time
import socket
import ipaddress
import re

def main():
    while True:
        u_response = input("NIC IP: 1\nBMC IP: 2\nExit: 3 ")
        #basic user repsonse, to be checked. 
        if u_response.isdigit():
            u_response = int(u_response)
            match u_response:
                case 1:
                    sys.stdout.write("Input IP: ")
                    sys.stdout.flush()
                    u_reply = sys.stdin.readline()
                    return [(u_reply), (u_response), (False)]
                case 2:
                    sys.stdout.write("Input IP: ")
                    sys.stdout.flush()
                    u_reply = sys.stdin.readline()   
                    return [(u_reply), (u_response), (False)]
                case 3:
                    print("Thank you for using the script.")
                    return
                case _:
                    print("Invalid response")
                
        else:
            print("Invalid response")    

#This will validate the ip / IPV4
def ip_validation():
    ip_check = main()
    ip_grab = ip_check[0]
    

ip_validation()

tough breach
#

and if you don't care about the flush, you can just do u_reply = input("Input IP: ") and forget all of the sys nonsense (this isn't C)

warm linden
#

Okay the only reason I did it was to intake the IP address.

frail thistle
#

oh you edited lol

tough breach
#

already edited

#

haha noticed that too

frail thistle
#

ok sorry

tough breach
#

and you can unpack each return value by doing ```py
def main():

...

return u_reply, u_response, False

def ip_validation():
ip, menu_option, validated = main()
print(ip)

#

you've got a lot of extra []'s and ()'s

#

also kinda random, but it feels like these function names should be swapped

#

main should be ip_validation and ip_validation should be main

#

also note that if you enter option 3 then your code will break because nothing gets returned

warm linden
#

could I add a break or something else?

#

I'm editing it now

tough breach
#

well eventually you'll have to return something

#

I just ranted about returns like this in another server: #791697255835893821 message

#

if you want to read that, go ahead

#

TL;DR you should always be returning the same "type of thing"

#

for example

def ip_validation():
  if choice == 1:
    ip = input()
    return ip, ip_is_valid(ip)
  elif choice == 3:
    return "<no entry>", False
#

this way, you always have an "ip" string and a "valid" boolean to work with

warm linden
#

ahhhh

tough breach
warm linden
#

I will read into that I appreciate it, all of your suggestions worked

#

import subprocess
import sys
import time
import socket
import ipaddress
import re

def ip_validation():
    while True:
        u_response = input("NIC IP: 1\nBMC IP: 2\nExit: 3 ")
        #basic user repsonse, to be checked. 
        if u_response.isdigit():
            u_response = int(u_response)
            match u_response:
                case 1:
                    u_reply = input("Input IP: ")
                    return [(u_reply), (u_response), (False)]
                case 2:
                    u_reply = input("Input IP: ")
                    return [(u_reply), (u_response), (False)]
                case 3:
                    print("Thank you for using the script.")
                    return
                case _:
                    print("Invalid response")
                
        else:
            print("Invalid response")    

#This will validate the ip / IPV4
def main():
    ip, menu_option, validated = ip_validation()
    try:
        ip_object = ipaddress.ip_address(ip)
        print('The IP address' ,{ip_object},'is valid.')
        return ip
    except ValueError:
        print('The IP address' ,{ip_object}, 'is not valid.')    



ip_validation() ```
#

Works like a charm now

#

@tough breach

tough breach
#

nice glad you got it working

warm linden
#

Now to work on the subprocess part and piping data from bash

#

But thanks, now in the future I can optimize code like this faster

hybrid spadeBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.