Reputation: 88
I want know how to pass information from one python program to another. Basically, I will open one python program which uses the os.system(file) command to execute another pytgon program. Let's take an example:
The "Parent" program:
import file #file is the child
import os
num=int(input("Enter number: "))
if num%2==0:
os.system('python file.py')
else:
pass
Now the "Child" program:
name=input("Enter Name: ")
age=int(input("Enter age: "))
print("Hi",name)
So in the example, when the user enters an even number, the program starts up the child program, which in turn will ask the user his name and age.
Now my question is this: If I want to bring back the information (name and age) entered in the child program back to the parent program, how do I do it?
Upvotes: 3
Views: 186
Reputation: 11
Upvotes: 0
Reputation: 13079
Using import
, you can access variables defined in another module. But in this case, the clean way to do this will be to put the code in the "child" [see footnote] inside a function, so that it is not run when the module is imported (which should usually be near the top of the module that does the import) but when you actually want to call the function -- so that the questions are only asked if you actually enter an even number. For example:
main.py
import myfile
num = int(input("Enter number: "))
if num%2==0:
name, age = myfile.get_name_and_age()
print("The name is ", name)
myfile.py
def get_name_and_age():
name=input("Enter Name: ")
age=int(input("Enter age: "))
print("Hi",name)
return name, age
Upvotes: 7