Sumathi Iyengar
Sumathi Iyengar

Reputation: 88

How to pass information between different python programs

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

Answers (2)

Mykola Murha
Mykola Murha

Reputation: 11

  1. Shared memory objects - platform depended feature. - not good solution.
  2. Simple files. - bad solution.
  3. ZeroMQ https://www.google.com/url?sa=t&source=web&rct=j&url=https://zeromq.org/&ved=2ahUKEwjFw9zJy63xAhVBlosKHTx1AWQQFjABegQICBAC&usg=AOvVaw29tSOVdy8XLINq5KCJc0WD , GCP Pub/Sub https://www.google.com/url?sa=t&source=web&rct=j&url=https://cloud.google.com/pubsub&ved=2ahUKEwjukOLhy63xAhVyoosKHZXXA-cQFjAAegQIGxAC&usg=AOvVaw380hk9SKYYO-19Aiqvhmj7 AWS SNS https://aws.amazon.com/sns/ ... - may be the best solution for.
  4. Man, use Flask and REST approach... or RPC, but REST is better

Upvotes: 0

alani
alani

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
  • Note: I have kept your use of the word "child" above based on the subprocess that you were using -- but the approach shown here is not using parent and child processes. Everything is run in the same python process if you do it this way.

Upvotes: 7

Related Questions