简体   繁体   English

如何让一个 python 文件要求用户输入,然后将此输入传递给第二个 .py 文件?

[英]How can I make one python file ask for user input and then pass this input to a second .py file?

I have an analyze.py file that performs three steps:我有一个执行三个步骤的analyze.py 文件:

  1. it imports a .csv file as a numpy array;它将 .csv 文件作为 numpy 数组导入;
  2. it asks for user input (eg x=input ('Enter a number by which you want to multiply your array?')它要求用户输入(例如x=input ('Enter a number by which you want to multiply your array?')
  3. uses that input to perform some array operations (eg output_array=csv_array*x ).使用该输入来执行一些数组操作(例如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).在第 3 步之后,我想关闭现有窗口并自动运行第二个 .py 文件来导入新数组 (output_array)。

In other words, I would like to pass a user-input variable from one py file to another.换句话说,我想将一个用户输入变量从一个 py 文件传递​​到另一个。 How can I do it?我该怎么做?

Please note that I am aware of similar questions (eg How can I make one python file run another? ), but I cannot guess how to deal with user input.请注意,我知道类似的问题(例如, 如何让一个 python 文件运行另一个? ),但我无法猜测如何处理用户输入。

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并在argsv中使用script2来读取相关参数。

$ python script2.py arg1 arg2

>>> import sys
>>> len(sys.argv) # 3

One way is to use subprocess.run to execute the second python file.一种方法是使用subprocess.run来执行第二个 python 文件。 This way you can pass the input array as argument to the second python file.这样您就可以将输入数组作为参数传递给第二个 python 文件。

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第二个 python 文件中的参数解析 # 标准库有 argparse 模块

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM