0

I have an analyze.py file that performs three steps:

  1. it imports a .csv file as a numpy array;
  2. it asks for user input (e.g. x=input ('Enter a number by which you want to multiply your array?')
  3. uses that input to perform some array operations (e.g. output_array=csv_array*x).

After step 3, I would like to close the existing window and automatically run a second .py file which imports the new array (output_array).

In other words, I would like to pass a user-input variable from one py file to another. How can I do it?

Please note that I am aware of similar questions (e.g. How can I make one python file run another?), but I cannot guess how to deal with user input.

Axblert
  • 556
  • 4
  • 19
Andrea
  • 1
  • Would it be a possibility to store the user output in a config file? That is how I have set up a similar project of mine. The second script extracts the necessary information from this file. – Tim Stack Dec 24 '19 at 12:00
  • Hi and welcome to SO. Please take the time to read the [How to Ask](https://stackoverflow.com/help/how-to-ask) section in order to understand how to post a good question so that the community can assist you. Please edit your post and add a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) and any errors or logs you might get. – Daniel Ocando Dec 24 '19 at 12:05

2 Answers2

0

There are several ways to approach this problem.

  • Use script args
  • Write to file and read the same file
  • Using message queues and workers (Much more complicated)

I would suggest you go with the first approach and use arguments for the second script. You can call you script like this: python script2.py arg1 arg2 and use argsv in the script2 to read related arguments.

$ python script2.py arg1 arg2

>>> import sys
>>> len(sys.argv) # 3
nima
  • 1,645
  • 9
  • 18
0

One way is to use subprocess.run to execute the second python file. This way you can pass the input array as argument to the second python file.

from subrocess import run
command = []
command.append(PYTHON_EXECUTABLE_PATH)
command.append(SECOND_FILE_PATH)
command.append(array_converted_to_string) # e.g. separate array elements with dashes '-'
completed_process = run(command, capture_output=True, text=True) 

So three things for you to implement:

  • a function to convert an array to a string
  • a function to do the conversion back
  • argument parsing in the second python file # standard library has the argparse module for that
Fakher Mokadem
  • 1,059
  • 1
  • 8
  • 22