有没有任何方法可以将输入提示的值传递给其他python脚本调用的python脚本



为了更好地理解,

示例2.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)

示例1.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,它又调用了另一个脚本并等待输入。

注:

  • 我不能在example2.py上做任何事情,它不是我的
  • 我只能对example1.py进行更改并将参数传递给example1.py
  • 我知道会为example2.py创建一个进程,但不确定是否将这些参数传递给进程IO
  • 实际代码不同,为了便于理解,我制作了example1.pyexample2.py

我无法从这些链接中获得任何想法:

从另一个脚本启动python脚本,子流程参数中包含参数

如何从另一个python脚本文件中执行带有参数的python脚本文件

请分享你对此的想法,并帮助我解决这个问题。如果需要,请不要介意编辑这个问题。我对模块ossubprocess完全陌生。

考虑要运行的文件:

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("1n2n3n", "utf-8"))
print(out.decode('utf-8'))

结果是:

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

阅读文档&此处的示例可了解更多详细信息。

我已经将代码升级到python3,因为python2是EOL。

p.S:我在这里使用shell=True是为了方便,但你可能不应该使用

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

您可以在示例2中使用int(input(((

一种简单的方法是使用一个脚本中的stdout将值馈送到另一个脚本。这里有一个使用python的例子|"命令和stdout。pipe命令重定向文件的输出,并将其用作链中下一个文件的输入

python example1.py | example2.py

代码输出:

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

示例1.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/