2964502
2964502

Reputation: 4499

input result from one program file into another program in python

The first python program called first.py includes the following code:

print ('my name is viena')

How can I input the result from that first program, i.e., 'my name is viena' as input into my second program called second.py which includes the following code:

question = 'what\'s your name?'
answer = ?????HERE HOW TO INPUT THE RESULT FROM FIRST PROGRAM

print (answer)
my name is viena

Note: There should be two different python script files as I mentioned in the question.

Upvotes: 1

Views: 205

Answers (2)

falsetru
falsetru

Reputation: 369444

How about change the first script as importable module:

# Changed the print function call with function.
def my_name():
    return 'my name is viena'

if __name__ == '__main__':
    print(my_name())

Another script can now import the first script using import statement, and use its functions.

import name_of_the_first_script

question = "what's your name?"
answer = name_of_the_first_script.my_name()

Upvotes: 1

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72855

If you can wrap the print statement in your first program inside a function (say print_name) , then you can so something like

import first
first.print_name()

to get the name.

For a completely general purpose solution that involves shelling out, take a look at the subprocess module.

Upvotes: 1

Related Questions