-1

How do I make this work? I tried looking in websites, but to no avail, I need this to work because I want to use it instead of running the files separately, so can anyone help me with this code?

I need to know what is wrong here.

input=("input 1 for encoder and 2 for decoder: ")
if input=1 open encoder.py
if input=2 open decoder.py

edit: this question is different and not a duplicate because this question was asking on how to run a python script based on the user input, e.g. user inputs 1 then python script encoder is ran

if option == "1":
    import encoder
elif option == "2":
    import decoder

code is from sr0812 it is a different implementation here

  • Take a look at this post - https://stackoverflow.com/questions/7974849/how-can-i-make-one-python-file-run-another – sr0812 Jan 22 '22 at 03:36
  • it not the same implementation – moongazer 07 Jan 25 '22 at 23:27
  • this question https://stackoverflow.com/questions/7974849/how-can-i-make-one-python-file-run-another is different because it's about running a python script automatically but my question is asking on how to make a python script run different scripts based on the user's input eg input = 1 it will run encoder.py but if its input = 2 it runs decoder.py – moongazer 07 Jan 25 '22 at 23:31

1 Answers1

0

There are multiple ways to do this -

Method 1 -

import encoder

Note - this only works once in the entire program

Method 2 -

exec(open('decoder.py').read())

Note - this is unsafe and you should avoid when possible

Method 3 -

os.system('python file.py')

Note - this is very hacky and you shouldn't use it much

So this should be the solution you are looking for -

import os

option = input("input 1 for encoder and 2 for decoder: ")
if option == "1":
    import encoder
elif option == "2":
    import decoder

Source - How can I make one python file run another?

sr0812
  • 324
  • 1
  • 9