【问题标题】:How to pass the string from php to tcl and execute the script如何将字符串从php传递到tcl并执行脚本
【发布时间】:2018-09-12 12:55:57
【问题描述】:

我想从我的 php 中传递字符串,比如

<?php
str1="string to pass"
#not sure about passthru
?>

还有我的tcl 脚本

set new [exec $str1]#str1 from php
puts $new

这可能吗?请让我知道我对此感到困惑

【问题讨论】:

    标签: php string tcl passthru


    【解决方案1】:

    最简单的机制是将 Tcl 脚本作为一个子进程运行,该子进程运行一个接收脚本(您可能将其放在与 PHP 代码相同的目录中,或者放在其他位置),它会解码它传递的参数以及您对它们的要求。

    所以,在 PHP 方面,您可能会这样做(注意 重要 在此处使用 escapeshellarg!我建议在测试用例中使用带空格的字符串,以确定您的代码是否正确引用了内容):

    <?php
    $str1 = "Stack Overflow!!!";
    $cmd = "tclsh mycode.tcl " . escapeshellarg($str1);
    $output = shell_exec($cmd);
    echo $output;
    echo $output;
    ?>
    

    在 Tcl 方面,参数(脚本名称之后)被放在全局 argv 变量的列表中。该脚本可以通过任意数量的列表操作将它们拉出来。这是一种方法,lindex:

    set msg [lindex $argv 0]
    # do something with the value from the argument
    puts "Hello to '$msg' from a Tcl script running inside PHP."
    

    另一种方法是使用lassign:

    lassign $argv msg
    puts "Hello to '$msg' from a Tcl script running inside PHP."
    

    但是请注意(如果您使用 Tcl 的 exec 来调用子程序),Tcl 会有效地自动为您引用参数。 (实际上,出于技术原因,它确实在 Windows 上这样做了。)Tcl 不需要像 escapeshellarg 这样的东西,因为它将参数作为字符串序列,而不是单个字符串,因此更了解正在发生的事情。


    传递值的其他选项是通过环境变量、管道、文件内容和套接字。 (或者更奇特的东西。)进程间通信的一般主题在两种语言中都可能变得非常复杂,并且涉及很多权衡;您需要非常确定自己总体上要做什么才能明智地选择一个选项。

    【讨论】:

      【解决方案2】:

      这是可能的。

      test.php

      <?php
      $str1="Stackoverflow!!!";
      $cmd = "tclsh mycode.tcl $str1";
      $output = shell_exec($cmd);
      echo $output;
      ?>
      

      mycode.tcl

      set command_line_arg [lindex $argv 0]
      puts $command_line_arg 
      

      【讨论】:

      • 你能解释一下 $argv 是什么吗?
      • 还有一件事,如果我在本地主机中运行 php 代码,它可以触发我服务器中的 tcl 脚本?
      • @ArunBaskar :是的,它可以。请参阅here 了解argv 的用法。
      • 我在 localhost 中运行您的 php 代码,但在第 2 行出现解析错误。
      • @ArunBaskar :修复它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-10
      • 1970-01-01
      相关资源
      最近更新 更多