如何嵌套为自动化目的输入变量的脚本?

问题描述 投票:2回答:2

我正在创建一个python脚本(cmd_exec.py)来打开另一个python脚本(entername.py)。如何嵌套它以便脚本输入字符串并自动执行输入按钮?试图记住有关输入的ASCII输入代码的问题,但找不到它。因此,当我在powershell中运行cmd_exec.py时,它将显示"Hello foo"

cmd_exec.py:

import subprocess, sys

p = subprocess.Popen(["powershell.exe", "py C:\\Users\\uname\\PProjects\\cmdauto\\entername.py"], stdout=sys.stdout)
p.communicate()

我希望maname变量插入到entername.py脚本和脚本中执行/按下回车键。因此,当我运行cmd_exec.py脚本时,我会看到它自己完成并打印出"Hello foo"

entername.py:

maname = "foo"
person = input('Enter your name: ')
print('Hello', person)
python subprocess sys
2个回答
0
投票

不确定这是否有帮助,或者这是否适用于您,但在Bash中,您可以使用'<'运算符指定输入。

例如,如果你有一个python文件program.py,你的输入在input.txt中就可以运行了

$ python3 program.py < input.txt

除非有其他限制,否则您可能希望采用此方法


0
投票

您可能正在寻找sys.argvsubprocess.getstatusoutput()

import subprocess
maname = "foo"
person = input('Enter your name: ')
print('Hello', person)
# not  sure why powershell is here, normally would be only `python C:\\Users\\uname\\PProjects\\cmdauto\\entername.py {person}`
x = subprocess.getstatusoutput(f"powershell.exe 'py C:\\Users\\uname\\PProjects\\cmdauto\\entername.py {person}'") 
print(x)
# (0, 'python f:\\entername.py')

# entername.py 
import sys
person = int(sys.argv[1]) # get the 2nd item on `argv` list, the 1st is the script name
© www.soinside.com 2019 - 2024. All rights reserved.