【问题标题】:How to nest script that inputs variable for automation purposes?如何嵌套用于自动化目的的输入变量的脚本?
【发布时间】:2019-08-27 19:19:20
【问题描述】:

我正在创建一个 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)

【问题讨论】:

  • 我不确定我是否正确理解了您的问题。为什么需要 2 个脚本? subprocess.getoutput(cmd) 会帮助你吗? docs.python.org/3/library/subprocess.html#subprocess.getoutput.
  • @PedroLobito 我实际上要运行 sqlmap.py,但现在无法让它在这台机器上运行。所以我把这两个简单的脚本放在一起提问,但原理是一样的。当我运行 sqlmap.py 时,它会在某些问题上问我是或否。我想用脚本自动化这个过程,这样在运行 sqlmap.py 时它会自动为我输入“y”。

标签: python subprocess sys


【解决方案1】:

不确定这是否有帮助或是否适合您,但在 Bash 中,您可以使用“

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

$ python3 program.py < input.txt

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

【讨论】:

    【解决方案2】:

    您可能正在寻找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
    

    【讨论】:

    • 它仍然要我输入我的名字。 PS C:\Users\uname\PProjects\cmdauto&gt; py .\cmd_exec.py Enter your name: Hello (0, 'py entername.py ') PS C:\Users\uname\PProjects\cmdauto&gt;
    猜你喜欢
    • 1970-01-01
    • 2021-11-11
    • 2014-03-04
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多