1

I am totally new to subprocess and need to be able to send a variable from one python file to another using this library.

I have a little idea of how to send the data from the master file (something like this?):

p = subprocess.Popen(['python', 'slave.py'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
stdout_data = p.communicate(input='string')

But how do I call that variable in the other file?

Unfortunately, I cannot use any other module because of the nature of my project.

Byrrell
  • 37
  • 4

1 Answers1

2

Your description is a little vague, but to answer your question as I understand it:

if your slave.py is executed every time you need to pass it a variable, you can pass it as an argument on the cli.

var1='simple data structure such as string, int etc.'
subprocess.call(['python', 'slave.py', var1])`

In slave.py you can then get this variable from sys.argv:

import sys
name_of_program = sys.argv[0]
var1 = sys.argv[1]

If your slave.py is running continuously there are several ways to communicate between processes on a same computer system:

  • Remote Procedure Calls - RPC
  • Shared Memory - See this SO thread
  • Using stdin as suggested in the comments (only for simple data structures like strings, int etc)
ege
  • 774
  • 5
  • 19
  • Ok, so I replaced `.call` with `.Popen` and now it passes the variable, while running both programs synchronously - just what I needed to do! – Byrrell Dec 03 '18 at 17:16