有什么方法可以将值传递给其他 python 脚本调用的 python 脚本的输入提示吗?

Is there any way to pass values to input prompt to the python script which was called by other python script?

为了更好的理解,

example2.py

    a = raw_input("Enter 1st number: ")
    b = raw_input("Enter 2nd number: ")
    *some code here*
    c = raw_input("Enter 3rd number: ")
    s = a+b+c
    print(s)

example1.py

    import os
    os.system('python example2.py')
    <need logic to address the input prompts in example2.py>
    <something to pass like **python example2.py 1 2 3**>

我想通过查看这些脚本,您可以找到我要找的东西吗?让我解释一次,以便更好地理解。有两个文件 example1.pyexample2.py。现在,我从我的 shell 调用了 example1.py,后者又调用了另一个脚本并等待输入。

备注:

我无法从这些链接中掌握任何想法:

how to execute a python script file with an argument from inside another python script file

请分享您对此的看法并帮助我解决此问题。如果需要,请不要介意编辑问题。我对模块 ossubprocess.

完全陌生

从 Python 3 开始,raw_input() 已重命名为 input()。

您可以在示例 2

中使用 int ( input ( ) )

考虑文件 运行:

a = int(input("Enter 1st number: "))
b = int(input("Enter 2nd number: "))
# code
c = int(input("Enter 3rd number: "))
s = a+b+c
print(s)

您可以使用 subprocess 模块从 python 运行 此文件。

import subprocess

proc = subprocess.Popen(['python', 'a.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, _ = proc.communicate(bytes("1\n2\n3\n", "utf-8"))
print(out.decode('utf-8'))

这导致:

Enter 1st number: Enter 2nd number: Enter 3rd number: 6

阅读文档和示例 here 了解更多详情。

我已将代码升级到 python3,因为 python2 已停产。

P.S:为了方便起见,我在这里使用了 shell=True - 但您可能不应该

一种简单的方法是使用一个脚本的标准输出将值输入另一个脚本。 这是一个使用 python 的示例,管道“|”命令和标准输出。管道命令重定向文件的输出并将其用作链中下一个文件的输入

python example1.py | example2.py

代码输出:

Enter 1st number: number is 1
Enter 2nd number: number is 2

example1.py代码:

print(1)
print(2)

example2.py代码:

a = input("Enter 1st number: ")
print("number is",a)

b = input("Enter 2nd number: ")
print("number is",b)

参考:https://www.geeksforgeeks.org/piping-in-unix-or-linux/