LinuxQuestions.org
Latest LQ Deal: Latest LQ Deals
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 04-19-2017, 08:28 AM   #1
bindo
LQ Newbie
 
Registered: Apr 2017
Posts: 6

Rep: Reputation: Disabled
Talking Python how to assign user inputs to variables


Hello all,

My first post here. Newbie to python and I want to improve the below code mainly for learning purpose. Let me first post it and then explain how I want to improve it.

Code:
VAR1, VAR2, VAR3= raw_input("Enter ip, port and name seperated by colan").split(":")
   ##user input should be something like, 1.1.1.1:422:name1

template ="""frontend fe:{0}:bind:{1}
        mode tcp
        bind {0}:{1} name {2}"""
  
BLOCK = template.format(VAR1,VAR2,VAR3)
  
with open("file.txt", "a") as myfile:
    myfile.write(BLOCK)
As you can see I'm appending to the "file.txt" based on user inputs. Once the user specify the ip address and the port (i.e: 10.1.2.2:443:somename) it would construct the text in variable "template" sending the correct value to the corresponding "{}".

I need to take this further and do the following. I'm really at a loss here guys.

- I want to get the user to specify the raw_input as a command line argument (i.e ./script.py FE-<name>:<ip>:<port> | BE-<name><ip>:<port>).

- I want to add another part to the template called "backend bk:<somename>:<someip>:<someport>". Script should pick up the correct user input to the right section (ie: "FE-<name>:<ip>:<port>" to the "frontend fe" section and "BE-<name><ip>:<port>" to the backend section.

- once user is done inputting the parameters I want to restart a service i.e:service abc restart. Please note that I want to wait before user adds all the entries before restarting the service.

Please help out gentleman. I really want to come up to speed.
many thanks in advance

-Bindo
 
Old 04-19-2017, 01:40 PM   #2
astrogeek
Moderator
 
Registered: Oct 2008
Distribution: Slackware [64]-X.{0|1|2|37|-current} ::12<=X<=15, FreeBSD_12{.0|.1}
Posts: 6,263
Blog Entries: 24

Rep: Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194
raw_input is for processing interactive user input.

If you want to pass and process command line args then what you probably need are optparse or argparse, depending on Python version.

As far as the other sections of the code, what to do with those args, it would be more helpful if you could show us what you have done and what parts you are having trouble with. Whlie people here are happy to help, we cannot write the code for you.

Last edited by astrogeek; 04-19-2017 at 01:42 PM. Reason: hilight, typo
 
Old 04-20-2017, 01:22 AM   #3
bindo
LQ Newbie
 
Registered: Apr 2017
Posts: 6

Original Poster
Rep: Reputation: Disabled
Thanks astro for the advice. Well I wrote the below code and it doesn't get me anywhere.

Code:
#!/usr/bin/python
import argparse
import re
import string

p = argparse.ArgumentParser()
p.add_argument("INPUT")  
args = p.parse_args()
KKK= args.INPUT
bb=re.split(":|,", KKK)

def func_three(help):
    for i in help:
        #print help
        return help

#func_three(bb[0:3])
YY = var1, var2, var3 = func_three(bb[0:3])
print YY
The way to run this script should be "script.py <IP>:<PORT:<HOSTNAME>". i.e: script.py 192.168.1.10:80:name1 172.25.16.2:100:name3

As you can see if one argument is passed I have no problems. But when there are more arguments I cant determine how to workout the regexes and get this done via a loop.

So to recap, this is how i want the output to look like to proceed further. Please help out.

192.168.1.10
80
name1

172.25.16.2
100
name2
 
Old 04-20-2017, 01:48 AM   #4
pan64
LQ Addict
 
Registered: Mar 2012
Location: Hungary
Distribution: debian/ubuntu/suse ...
Posts: 21,830

Rep: Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308Reputation: 7308
I would try to use the argv array http://www.pythonforbeginners.com/sy...ython-sys-argv http://www.pythonforbeginners.com/ar...with-sys-argv:
Code:
for var in sys.argv[1:]:
    data = re.split(":|,", var)
    print data[0]
    print data[1]
    print data[2]
 
2 members found this post helpful.
Old 04-20-2017, 03:28 AM   #5
camp0
Member
 
Registered: Dec 2016
Location: Dublin
Distribution: Fedora
Posts: 70

Rep: Reputation: 4
I prefer the optparse style

Code:
import optparse

def option_parser():

    def get_comma_separated_args(option, opt, value, parser):
        setattr(parser.values, option.dest, value.split(','))

    p = optparse.OptionParser()

    p.add_option("-u","--url", dest="url",
        default="http://www.google.com", type="string",
        help="Sets the URL. Default value [%default]")

    p.add_option("-v", "--verbose",dest="verbose", default=False, action="store_true",
        help="Shows extra messages.")

    return p

if __name__ == '__main__':

    (options, args) = option_parser().parse_args()
 
1 members found this post helpful.
Old 04-20-2017, 09:34 AM   #6
bindo
LQ Newbie
 
Registered: Apr 2017
Posts: 6

Original Poster
Rep: Reputation: Disabled
Thanks all for trying to help out. I will try the suggestions out and get back to you. Its is very late in the night here in this part of the world/. Thanks once again.

-Bindo
 
Old 04-26-2017, 07:10 AM   #7
bindo
LQ Newbie
 
Registered: Apr 2017
Posts: 6

Original Poster
Rep: Reputation: Disabled
Smile

I appologize for not having replied much sooner as I was taken ill.

Both solutions work and thanks so much for helping out Camp0 and and Pan64. You guys rock.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
[SOLVED] (BASH) How to assign 2 variables to same line? Dick Dastardly Programming 10 01-15-2012 09:17 AM
assign commands to Variables tazbv Programming 2 08-03-2007 02:07 AM
python, os.system() function. howto use python variables? jhwilliams Programming 5 07-28-2007 01:56 AM
Perl + Java assign variables arash8m Programming 1 07-17-2007 01:37 PM
Using letters/strings to assign variables in python Colonel Panic Programming 0 09-14-2001 10:13 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 01:31 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration