sur*_*rya 6 python parameters arguments input python-3.x
为了更好地理解,
示例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)
Run Code Online (Sandbox Code Playgroud)
示例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**>
Run Code Online (Sandbox Code Playgroud)
我想通过查看这些脚本你可以得到我正在寻找的东西?让我解释一次以便更好地理解。有两个文件example1.py和example2.py. 现在,我example1.py从 shell 调用,shell 又调用另一个脚本并等待输入。
笔记:
example2.py不属于我的 进行任何操作。example1.py并将参数传递给example1.pyexample2.py,但不确定是否将这些参数传递给进程 IO。example1.py而精心设计的。example2.py我无法从这些链接中掌握任何想法:
如何使用另一个 python 脚本文件中的参数执行 python 脚本文件
请分享您对此的想法并帮助我解决这个问题。如果需要,请不要介意编辑问题。我对该模块完全陌生os。subprocess
考虑要运行的文件:
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)
Run Code Online (Sandbox Code Playgroud)
您可以使用该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'))
Run Code Online (Sandbox Code Playgroud)
结果是:
Enter 1st number: Enter 2nd number: Enter 3rd number: 6
Run Code Online (Sandbox Code Playgroud)
请阅读此处的文档和示例以了解更多详细信息。
由于 python2 已停产,我已将代码升级到 python3。
PS:我在这里使用是shell=True为了方便 - 但你可能不应该