【问题标题】:How to run .EXE with inputs on terminal in Unix/Linux?如何在 Unix/Linux 的终端上运行带有输入的 .EXE?
【发布时间】:2017-01-26 21:59:31
【问题描述】:

我有一个可执行文件 (Something.exe),当我运行它时它接受两个输入。 例如它做了这样的事情:

    My-MacBook:Folder my$ ./Something.exe
    Enter first input: someimage.tif
    Enter second input: x y z coordinates 
    123 456 23.00000 24.0000 59.345

我运行程序并在提示时分别输入两个输入,然后程序给出结果。

但是,如何将整个过程输入一行,意思是:

    My-MacBook:Folder my$ ./Something.exe someimage.tif x y z coordinates
    123 456 23.00000 24.0000 59.345

如何在终端上的一行中执行此操作,这样我就不必在出现提示时输入输入?我需要在程序代码中调整什么吗?该程序是用 Fortran 90 编写的。

【问题讨论】:

  • 如果您想调整程序,请寻找“获取参数”...genomeek.wordpress.com/2012/02/09/…
  • @Mark Setchell 谢谢!我会检查一下。
  • 你的意思是你想用相同的图像但不同的坐标多次运行程序?如果你得到你想要的答案,也许你可以显示你将运行的前 3 个命令......

标签: linux shell unix terminal


【解决方案1】:

如果程序只是从标准输入读取,你可以简单地做

printf '%s\n%s\n' 'someimage.tif' 'x y z coordinates' | ./Something.exe

或者如果你使用的 shell 是 bash:

echo $'someimage.tif\nx y z coordinates' | ./Something.exe

【讨论】:

  • 您好! printf 工作。谢谢!!如果不是太麻烦,您介意解释一下'%s\n%s\n'是什么吗?
  • @Guest 命令见man 1 printf,格式字符串见man 3 printf。基本上,第一个参数是一个描述如何格式化输出的字符串。 %s 表示“在此处输出下一个参数(作为字符串)”; \n 表示“输出换行符(换行符)”。
【解决方案2】:

将命令行参数推送到交互式命令行程序的一种经典方法是使用 expect 脚本。对于您的示例 exe,这是一个应该可以工作的期望脚本:

#!/usr/bin/env expect
set tif [lindex $argv 0]
set x [lindex $argv 1] 
set y [lindex $argv 2]
set z [lindex $argv 3]
set coords "$x $y $z"
spawn ./Something.exe
match_max 100000
expect "first input:"
send -- $tif
send -- "\r"
expect "second input:"
send -- $coords
send -- "\r"
expect eof

将其写入一个文件,例如,automate.exp,使其可执行,然后像这样运行它:

./automate.exp someimage.tif xcoord ycoord zcoord

【讨论】:

    【解决方案3】:

    恕我直言,最简单的方法是在Something.exe 周围“放置一个外壳包装器”。假设我们希望新命令为GoBaby,我们会将以下内容另存为GoBaby

    #!/bin/bash
    ################################################################################
    # GoBaby
    # Wrapper around Something.exe, to be used as:
    #
    # ./GoBaby image.tif "x y z"
    ################################################################################
    # Pick up the two parameters we were called with
    image=$1
    xyz=$2
    # Send the parameters into Something.exe
    { echo "$image"; echo "$xyz"; } | ./Something.exe
    

    然后,使包装脚本可执行(只需要一次):

    chmod +x GoBaby
    

    现在你可以运行了:

    ./GoBaby image.tif "x y z"
    

    【讨论】:

      猜你喜欢
      • 2020-01-08
      • 1970-01-01
      • 2019-07-04
      • 2017-06-11
      • 2017-07-06
      • 1970-01-01
      • 2015-11-20
      • 2020-02-16
      • 2018-09-23
      相关资源
      最近更新 更多