(From comments to question)
Consider the following files:
#-- b.py ----------------------------------------------------------------------------------
def main():
name = input("Enter your name: ") # Python 3, use raw_input for Python 2
print("Your name is:", name)
#-- a.py ----------------------------------------------------------------------------------
import json
# Some method of generating a json
j = json.dumps({'name': 'Alice'})
And you want to have b.py's main
function use the data in the json that is generated in a.py, instead of what main
prompts the user for.
In other words, in the above example, you'd want to have the program print Your name is: Alice
without prompting the user for input.
If that's the case, you might refactor your code to look something like:
#-- b.py ----------------------------------------------------------------------------------
def process(name):
print("Your name is:", name)
def get_user_input():
name = input("Enter your name: ") # Python 3, use raw_input for Python 2
process(name) # Prints: "Your name is: (whatever)"
#-- a.py ----------------------------------------------------------------------------------
import json
from b import process
# Some method of generating a json
j = json.dumps({'name': 'Alice'})
# (We created a json for no real reason, parse it back into a dict to access it)
d = json.loads(j)
# Call b.py's process function, and pass it the name in the json
process(d['name']) # Prints: "Your name is: Alice"
The "trick" here is to separate "jobs" that the main
function does into two separate functions.
- The first function (
process
), is given a name and "processes" it. In the example, all it does is print it out.
- One second function (named
get_user_input
in the refactoring) gets the user's input and passes it to the first function.
After doing this, you can skip the user input (since you don't need it, you want to use the JSON data) and call process
directly, even from other files.