[英]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 文件:
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?')
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.有几种方法可以解决这个问题。
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:所以你要实现三件事:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.