python script

Hi All,

I need a python script to do the following:

1. prompt user to answer choose from number 1-10.

2. take the input from user and based on the answer, call different python script based on case 1, case 2, case 3....

Could some one help me with this?
fireburn11Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

gelonidaCommented:
python2 or python3 ?
if the six module is installed then following code will run on both

import sys
from six.moves import input
from collections import OrderedDict
import subprocess

script_table = OrderedDict([
    ("1", [ "script1.py" ] ),
    ("2", [ "script_two.py" ] ),
    ("3", [ "script_two.py", "--with-an-option" ] ),
])

def show_choices(cmd_table):
    for key, command in cmd_table.items():
        print("Press %r to run the script %s" % (key, command))
    print("Press 'x' to exit\n")

while True:
    show_choices(script_table)
    choice = input("Please enter your choice:")
    if choice == "x":
        break
    if choice in script_table:
        command = [ sys.executable ] + script_table[choice]
        subprocess.call(command)
    else:
        print("Invalid choice %r" % choice)

Open in new window

0
fireburn11Author Commented:
I don't have six module installed. How do I install it ? Is there another way to do this ? It is bit complicated to understand...
0
peprCommented:
I am just guessing, but you actually may want not to call another Python script. Instead, you can use it as a module and call a function from inside the module. It is also very natural to write a xyz.py so that the same can be used both as a script called from a command line, and as a Python module.
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

gelonidaCommented:
if you don't have six, then do following:

try:
    input = raw_input
except:
    pass
import sys

from collections import OrderedDict
import subprocess

script_table = OrderedDict([
    ("1", [ "script1.py" ] ),
    ("2", [ "script_two.py" ] ),
    ("3", [ "script_two.py", "--with-an-option" ] ),
])

def show_choices(cmd_table):
    for key, command in cmd_table.items():
        print("Press %r to run the script %s" % (key, command))
    print("Press 'x' to exit\n")

while True:
    show_choices(script_table)
    choice = input("Please enter your choice:")
    if choice == "x":
        break
    if choice in script_table:
        command = [ sys.executable ] + script_table[choice]
        subprocess.call(command)
    else:
        print("Invalid choice %r" % choice)

Open in new window

0
gelonidaCommented:
if you want to call other functions, then use:
#!/usr/bin/env python

from collections import OrderedDict

try:
    input = raw_input
except:
    pass

def func1():
    print("this is func 1")


def func2(a, b):
    print("%r + %r = %r" % (a, b, a+b))

script_table = OrderedDict([
    ("1", ( func1, []) ),
    ("2", ( func2, [1, 2]) ),
    ("3", ( func2, [5, 9]) ),
])

def show_choices(cmd_table):
    for key, func_w_args in cmd_table.items():
        func, args = func_w_args
        print("Press %r to run function %s with %r" % 
                (key, func.__name__, args))
    print("Press 'x' to exit\n")

while True:
    show_choices(script_table)
    choice = input("Please enter your choice:")
    if choice == "x":
        break
    if choice in script_table:
        func, args = script_table[choice]
        result = func(*args)
        print("function was called and result is %r" % result)

    else:
        print("Invalid choice %r" % choice)

Open in new window


If you want to import (end execute) a file as a module:
#!/usr/bin/env python

from collections import OrderedDict
import importlib

try:
    input = raw_input
except:
    pass

def func1():
    print("this is func 1")


def func2(a, b):
    print("%r + %r = %r" % (a, b, a+b))

script_table = OrderedDict([
    # num,   # name of the python file without the .py
    ("1", "script1" ),  # will import script1.py
    ("2", "script_two" ), # will import script_two.py
])

def show_choices(cmd_table):
    for key, module in cmd_table.items():
        print("Press %r to run function %s" % 
                (key, module))
    print("Press 'x' to exit\n")

while True:
    show_choices(script_table)
    choice = input("Please enter your choice:")
    if choice == "x":
        break
    if choice in script_table:
        module_name = script_table[choice]
        importlib.import_module(module_name) # imports and executes other python file

    else:
        print("Invalid choice %r" % choice)

Open in new window


if you want to import a module and call a specifc function with specific arguments, then this would be again another solution
0
gelonidaCommented:
You might have noticed, that in the last example of my previous post
I forgot to remove the functions func1 and func2.
They can of course be deleted.

Now some more explanations:
The function to get user input was called raw_input() in python2 and is called imput() in python3.

The six module is one way to easier write code, that works in python2 and python3.

The trick with
try:
    input = raw_input
except:
    pass

Open in new window

does more or less the same thing, but looks uglier.

if you really want to enter numbers only and NEVER text, then python2 and python3 can both use the function int(input())


The idea of my code was to create a lookup table. as an Ordered Dict in which you store, which number corresponds to which python file.

if you really want to enter numbers only and never letters, then the code could use a list instead of a dict and would look like this:
#!/usr/bin/env python

import importlib

script_table = [
    "script1",  # will import script1.py
    "script_two", # will import script_two.py
    "script_3", # will import script_3.py
    ]

def show_choices(cmd_table):
    for key, module in enumerate(script_table, 1):
        print("Press %r to run function %s" % 
                    (key, module))
    print("type 0 to exit\n")

while True:
    show_choices(script_table)
    try:
        choice = int(input("Please enter your choice:")) # works for python 2 and 3
        if choice == 0:
            break
        module_name = script_table[choice-1]
    except:
        print("Invalid input %r" % choice)
        continue 

    importlib.import_module(module_name) # imports and executes other python file

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
fireburn11Author Commented:
Thanks alot! it works!
0
Suhas .QA ManagerCommented:
No comment has been added to this question in more than 21 days, so it is now classified as abandoned.

I have recommended this question be closed as follows:

Accept: gelonida (https:#a40801578)

If you feel this question should be closed differently, post an objection and the moderators will review all objections and close it as they feel fit. If no one objects, this question will be closed automatically the way described above.

suhasbharadwaj
Experts-Exchange Cleanup Volunteer
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Python

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.