How Can I call a Python Script From anonther Python Script
I tried using os system and tried using this
def run(runfile):
with open(runfile,"r") as rnf:
exec(rnf.read())
print ("Welcome")
print ("Programs.")
print ("1. Vowel Counter")
print ("2. Basic Calculator")
print ("3. Odd Even")
program = int(input("Select a Program by Choosing its number: "))
programs = ["1", "2", "3"]
if program == "1" :
execfile('VowelCounter.py')
There's no Error but it wont run the other py file
Even though python has the capabilities to run external script using exec and execfile, the more pythonic way of doing is by importing packages.
But I understand that you target can only be known at run time, you could use importlib, to import a package dynamically.
A sample is given below
# Order should be re arranged as per your need
programs = {
"1": {'package': "VowelCounter", "desc": "1. Vowel Counter"},
"2": {'package': "BasicCalculator", "desc": "2. Basic Calculator"}
}
for item in programs.values():
print(item['desc'])
program_idx = input("Select a Program by Choosing its number: ")
imp_module = importlib.import_module(programs[program_idx]['package'])
main_method = getattr(imp_module, "main")
main_method()
You are reading the program variable as int here
program = int(input("Select a Program by Choosing its number: "))
Then you are checking the value as string
if program == "1" :
It must be
if program == 1 :
I think that should be the problem. If not you will get the real problem after this!
import os
print("Welcome")
print("Programs.")
print("1. Vowel Counter")
print("2. Basic Calculator")
print("3. Odd Even")
program = input("Select a Program by Choosing its number: ")
programs = ["1", "2", "3"]
program_files = {'1': 'VowelCounter', '2': 'BasicCalculator', '3': 'OddEven'}
if program in "123" :
cmd = f'python {program_files[program]}.py'
print('Running -->', cmd)
os.system(cmd)
Related
I am coding a to-do app, but while matching the menu() function it gives a Syntax Error, the function returns the number of the option the user selected, this is the code:
# Imports
import time, os, random
from colorama import Fore, Back, Style
# Functions
def menu():
print(f"{Fore.BLUE}To-Do List!")
print(Style.RESET_ALL)
print(f"{Fore.GREEN}[1] ADD ITEM")
print(f"{Fore.RED}[2] REMOVE ITEM")
print(f"{Fore.BLUE}[3] SEE LIST")
option = int(input("Selection > "))
return option
# Variables
newItem = {
"name": "",
"description": "",
"date": "",
"priority": ""
}
todo = []
# Code
match menu():
case 1:
os.system("clear")
print(f"{Fore.GREEN}ADD ITEM TO LIST")
print(Style.RESET_ALL)
newItem["name"] = input("Item name > ")
newItem["description"] = input("Item description > ")
newItem["date"] = input("Item date > ")
newItem["priority"] = input("Item priority (low/med/high) > ")
todo.append(newItem)
print(todo)
input()
How can I solve it?
I tried changing the variable and using the match() statement a different way, it still has the same error.
As #CryptoFool allready mentioned in the comments, the match statement was added in python 3.10. Means, previous versions won't work.
Make shure to install a python version greater or equeal as 3.10, or use a workaround
Hello please forgive me if my question duplicate, I've searched previous questions and nothing seems to be quite the same. I'm working on a program that will scan a specific folder and search for specific file types to create a menu for a user to select. Once the user select the menu option the the corresponding file which is a power shell script. Currently My program does everything but run even a simple power shell script. I've attempted several configuration and it's not working. It would be great if someone can see what I may be doing wrong or provide me with some pointers. Code below.
##Text Menu Dynamic test
##version 1
## Created By Dragonshadow
## Code produce in Notpad++ For python v3.4.4
import os
import subprocess
import time
import pathlib
import logging
import fnmatch
import re
## Directory Enumerator
fileFolderLocationFilter = fnmatch.filter(os.listdir('C:\\Users\\myfolder\\Documents\\Automation_Scripts\\ENScripts\\'),"*.ps1")
selectedFile=""
## Menu defined setting veriables
def ENOC_menu():
files = fileFolderLocationFilter
counter = 1
print (20 * "=" , "Enoc Quick Menu" , 20 * "=")
enumFiles = list(enumerate(files))
for counter, value in enumFiles:
str = repr(counter) + ") " + repr(value);
print(str)
str = repr(counter+1) + ") Exit";
print(str)
print (57 * "_")
str = "Enter your choice [1 - " + repr((counter+1)) + "]:"
choice = int(input("Please Enter a Selection: "))
selectedFiles = enumFiles[choice]
return(selectedFiles[1])
if choice > counter :
choice = -1
elif choice != counter :
print("Please selecte a valid choice")
else:
selectedFiles = enumFiles[choice]
print(selectedFiles[1])
##selectedFiles = selectedFiles[1]
return choice
def you_sure():
opt = input("Are you sure Yes or No: ")
if opt=="Yes":
print("Continuing please wait this may take a moment...")
elif opt=="No":
print("returnig to Enoc Menu")
else: ##Stays in loop
print ("Please choose yes or no")
##count_down
def count_down ():
count_down = 10
while (count_down >= 0):
print(count_down)
count_down -= 1
if count_down == 0:
print("Task will continue")
break
##initiating loop
loop = True
while loop:
choice = ENOC_menu()
print ("\n" +"You selected "+ choice +"\n")
subprocess.call("C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe" + choice, shell=True)
##print ("---" +str(selectedFile))
You have probably already figured this out, but I the problem is in the subprocess.call() line. You are concatenating the powershell.exe path and the target file name together. See here:
>>> scriptToRun = "c:\\users\\Username\\Documents\\WindowsPowerShell\\classtestscript.ps1"
>>> powershellExe = "c:\\windows\\system32\\windowspowershell\\v1.0\\powershell.exe"
>>> print(powershellExe + scriptToRun)
c:\windows\system32\windowspowershell\v1.0\powershell.exec:\users\Username\Documents\WindowsPowerShell\classtestscript.ps1
Above, the two strings are stuck together without a space between them. Windows can't make sense of what you're trying to execute.
Put a space between the two two and subprocess.call() will understand what you're trying to do:
>>> print(powershellExe + ' ' + scriptToRun)
c:\windows\system32\windowspowershell\v1.0\powershell.exe c:\users\Username\Documents\WindowsPowerShell\classtestscript.ps1
I am extremely new to Python, and to programming in general, so I decided to write some basic code to help me learn the ins and outs of it. I decided to try making a database editor, and have developed the following code:
name = []
rank = []
age = []
cmd = input("Please enter a command: ")
def recall(item): #Prints all of the information for an individual when given his/her name
if item in name:
index = name.index(item) #Finds the position of the given name
print(name[index] + ", " + rank[index] + ", " + age[index]) #prints the element of every list with the position of the name used as input
else:
print("Invalid input. Please enter a valid input.")
def operation(cmd):
while cmd != "end":
if cmd == "recall":
print(name)
item = input("Please enter an input: ")
recall(item)
elif cmd == "add":
new_name = input("Please enter a new name: ")
name.append(new_name)
new_rank = input("Please enter a new rank: ")
rank.append(new_rank)
new_age = input("Please input new age: ")
age.append(new_age)
recall(new_name)
else:
print("Please input a valid command.")
else:
input("Press enter to quit.")
operation(cmd)
I want to be able to call operation(cmd), and from it be able to call as many functions/perform as many actions as I want. Unfortunately, it just infinitely prints one of the outcomes instead of letting me put in multiple commands.
How can I change this function so that I can call operation(cmd) once, and call the other functions repeatedly? Or is there a better way to go about doing this? Please keep in mind I am a beginner and just trying to learn, not a developer.
Take a look at your code:
while cmd != "end":
if cmd == "recall":
If you call operation with anything than "end", "recall" or "add", the condition within while is True, the next if is also True, but the subsequent ifs are false. Therefore, the function executes the following block
else:
print("Please input a valid command.")
and the while loop continues to its next lap. Since cmd hasn't changed, the same process continues over and over again.
You have not put anything in your code to show where operator_1, operator_2, and operator_3 come from, though you have hinted that operator_3 comes from the commandline.
You need to have some code to get the next value for "operator_3". This might be from a list of parameters to function_3, in which case you would get:
def function_3(operator_3):
for loopvariable in operator_3:
if loopvariable == some_value_1:
#(and so forth, then:)
function_3(["this","that","something","something else"])
Or, you might get it from input (by default, the keyboard):
def function_3():
read_from_keyboard=raw_input("First command:")
while (read_from_keyboard != "end"):
if read_from_keyboard == some_value_1:
#(and so forth, then at the end of your while loop, read the next line)
read_from_keyboard = raw_input("Next command:")
The problem is you only check operator_3 once in function_3, the second time you ask the user for an operator, you don't store its value, which is why its only running with one condition.
def function_3(operator_3):
while operator_3 != "end":
if operator_3 == some_value_1
function_1(operator_1)
elif operator_3 == some_value_2
function_2
else:
print("Enter valid operator.") # Here, the value of the input is lost
The logic you are trying to implement is the following:
Ask the user for some input.
Call function_3 with this input.
If the input is not end, run either function_1 or function_2.
Start again from step 1
However, you are missing #4 above, where you are trying to restart the loop again.
To fix this, make sure you store the value entered by the user when you prompt them for an operator. To do that, use the input function if you are using Python3, or raw_input if you are using Python2. These functions prompt the user for some input and then return that input to your program:
def function_3(operator_3):
while operator_3 != 'end':
if operator_3 == some_value_1:
function_1(operator_3)
elif operator_3 == some_value_2:
function_2(operator_3)
else:
operator_3 = input('Enter valid operator: ')
operator_3 = input('Enter operator or "end" to quit: ')
looks like you are trying to get input from the user, but you never implemented it in function_3...
def function_3(from_user):
while (from_user != "end"):
from_user = raw_input("enter a command: ")
if from_user == some_value_1:
# etc...
I'm building a Windows application using Python 2.7 that requires a simple console menu, ex:
Do something
Do something else
Exit
There will be several menus, the main menu will link to others. So I am attempting to avoid the scenario of having a bunch of stacks of if input == "1" code. Similar to this StackOverflow link. My below code is currently skipping the main menu and executing every option in my second menu. I've looked it over but I'm failing to see the logic in why it is performing the way it does.
computer = ""
# need a class for each of the options in power_menu
class power:
def logoff(self, computer):
print "logging off " + computer
def restart(self, computer):
print "restarting " + computer
def shutdown(self, computer):
print "shutting down " + computer
def set_computer():
global computer
#os.system("cls")
# optionally print the banner
computer = raw_input("Computer: ")
# check the computer is online
# move to the main menu with the computer parameter
menu().menu_main(computer)
def func_quit():
sys.exit()
def invalid(computer):
#os.system("cls")
print "INVALID CHOICE!"
menu().menu_main(computer)
class menu():
def menu_main(self, computer):
opts_main = {"1":("Power Options", self.menu_power(computer)),
"2":("Service Options", self.menu_service(computer)),
"3":("Service Tag & Warranty", self.menu_warranty(computer)),
"4":("User Options", self.menu_user(computer)),
"5":("Change Computer", set_computer),
"6":("Quit hd-con", func_quit)
}
for key in sorted(opts_main.keys()):
print "\t" + key + ": " + opts_main[key][0]
ans = raw_input("Selection: ")
try:
opts_main.get(ans, [None, invalid])[1]()
except Exception, e:
print e
#men_sel()
def menu_power(self, computer):
opts_power = {"1":("Logoff", power().logoff(computer)),
"2":("Restart", power().restart(computer)),
"3":("Shutdown", power().shutdown(computer)),
"4":("Main Menu", menu.menu_main),
"5":("Quit hd-con", func_quit)
}
for key2 in sorted(opts_power.keys()):
print "\t" + key2+": " + opts_power[key2][0]
ans2 = raw_input("Selection: ")
try:
opts_power.get(ans2)[1]()
#pow_sel()
except:
raise
My output for the above is looking like this.
Computer: asdf
logging off asdf
restarting asdf
shutting down asdf
1: Logoff
2: Restart
3: Shutdown
4: Main Menu
5: Quit
Selection:
I'm looking for guidance on using a dictionary for use in a console menu, fixes for the existing code, or a recommended direction to take this instead of what i'm looking at.
Thanks in advance.
Your assignment to the dictionary:
opts_main = {"1":("Power Options", self.menu_power(computer)), ...}
is calling menu_power, and storing the return value (None) in the tuple. You can use e.g. functools.partial to avoid this:
from functools import partial
opts_main = {"1":("Power Options", partial(self.menu_power, computer)), ...}
I apologize for how simplistic this may be, but I am a little confused looking at one part of this code.
# Geek Translator
# Demonstrates using dictionaries
geek = {"404": "clueless. From the web error message 404, meaning page not found.",
"Googling": "searching the Internet for background information on a person.",
"Keyboard Plague": "the collection of debris found in computer keyboards.",
"Link Rot" : "the process by which web page links become obsolete.",
"Percussive Maintainance" : "the act of striking an electronic device to make it work.",
"Uninstalled" : "being fired. Especially popular during the dot-bomb era."}
choice = None
while choice != "0":
print(
"""
Geek Translator
0 - Quit
1 - Look Up a Geek Term
2 - Add a Geek Term
3 - Redefine a Geek Term
4 - Delete a Geek Term
"""
)
choice = input("Choice: ")
print()
# exit
if choice == "0":
print("Good-bye.")
# get a definition
elif choice == "1":
term = input("What term do you want me to translate?: ")
if term in geek:
definition = geek[term]
print("\n", term, "means", definition)
else:
print("\nSorry, I don't know", term)
# add a term-definition pair
elif choice == "2":
term = input("What term do you want me to add?: ")
if term not in geek:
definition = input("\nWhat's the definition?: ")
geek[term] = definition
print("\n", term, "has been added.")
else:
print("\nThat term already exists! Try redefining it.")
# redefining an existing term
elif choice == "3":
term = input("What term do you want me to redefine?: ")
if term in geek:
definition = input("What's the new definition?: ")
geek[term] = definition
print("\n", term, "has been redefined.")
else:
print("\nThat term doesn't exist! Try adding it.")
# delete a term-definition pair
elif choice == "4":
input("What term do you want me to delete?")
if term in geek:
del geek[term]
print("\nOkay, I deleted", term)
else:
print("\nI can't do that!", term, "doesn't exist in the dictionary.")
# some unknown choice
else:
print("\nSorry, but", choice, "isn't a valid choice.")
input("\n\nPress the enter key to exit.")
I understand how all of this works with the exception of the print() function after choice = input(Choice: ")
Why is that there? If I remove it, nothing changes (as far as I can tell), so I was curious about its significance.
print() with no parameters prints a newline. The point is to show a blank line in the terminal output.
It prints a new line (which is visible as an empty line in the console output).
An empty print() outputs a newline, so maybe the only reason it's there is to add a newline?