dopuzf0898 2016-05-11 16:48
浏览 68
已采纳

从perl / php脚本执行终端命令是一个好习惯吗? [重复]

This question already has an answer here:

Like executing a command using backticks or exec() or system().

</div>
  • 写回答

4条回答 默认 最新

  • douli4852 2016-05-11 17:55
    关注

    Yes, this is bad practice in almost all cases! This is especially true if you have a choice.

    Executing external commands is:

    • Very hard to do correctly (but very easy to get sort-of-working). You can't just escape the shell args and call it a day, you have to account for potentially multiple levels of escaping for potentially different languages.

    • Slow. A fork+exec to e.g. rm is easily a thousand times slower than the corresponding syscall.

    • A rigid, error-prone and inexpressive integration point. You typically have to convert data to flat lists of strings and back. You can't use the language's features like exception handling, nested data structures or callbacks.

    Due to this, the following are BAD reasons to call external commands:

    • Not knowing how to do X in your language, but knowing a shell command for it. A typical example is cp -R foo bar.

    • Not knowing how something works, but knowing a shell oneliner that does it. A typical example is foo *.mp4 > >(tee file).

    • Not wanting to learn a new API for e.g. json or http, and instead using shell tools like jq or curl.

    However, if you are calling a program that does non-trivial things, that doesn't have a native library or bindings, AND that you know how to invoke with execve semantics (NOT system nor perl exec semantics that invoke shells), this is a valuable tool.

    Examples of good uses of executing external commands that follow all the above is invoking make to build a project from an installer, or running java -jar ... to start a Minecraft server.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案