NooBiieEE
NooBiieEE

Reputation: 1

Python calling PyFIles

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

Upvotes: 0

Views: 92

Answers (3)

Waket Zheng
Waket Zheng

Reputation: 6351

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)

Upvotes: 0

Sajeer Noohukannu
Sajeer Noohukannu

Reputation: 678

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()

Upvotes: 1

Kris
Kris

Reputation: 8853

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!

Upvotes: 0

Related Questions