加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

shell – 终端cd命令无法使用Scala脚本

发布时间:2020-12-15 21:57:34 所属栏目:安全 来源:网络整理
导读:我需要从 Scala脚本运行shell命令,我使用以下代码片段: import scala.sys.process.{Process,ProcessIO}val command = "ls /tmp"val process = Process(command)val processIO = new ProcessIO(_ = (),stdout = scala.io.Source.fromInputStream(stdout).get
我需要从 Scala脚本运行shell命令,我使用以下代码片段:

import scala.sys.process.{Process,ProcessIO}

val command = "ls /tmp"
val process = Process(command)

val processIO = new ProcessIO(_ => (),stdout => scala.io.Source.fromInputStream(stdout).getLines.foreach(println),_ => ())
process.run(processIO)

代码工作正常.我想知道为什么我得到

java.io.IOException: Cannot run program "cd": error=2,No such file or directory

一旦我将命令更改为cd / tmp&& ls哪个IMO相当于ls / tmp?

解决方法

从 Wikipedia on cd command开始:

[…] on Unix systems cd calls the chdir() POSIX C function. This means that when the command is executed,no new process is created to migrate to the other directory as is the case with other commands such as ls. Instead,the shell itself executes this command.

在那里甚至有关于Java的引用:

[…] neither the Java programming language nor the Java Virtual Machine supports chdir() directly; a change request remained open for over a decade while the team responsible for Java considered the alternatives,though by 2008 the request was denied after only limited support was introduced […]

亲自尝试一下:

$which ls
/bin/ls
$which cd
$

简单来说,cd不是你可以运行的程序(进程)(比如/ bin / ls) – 它更像是一个命令行指令.

你想达到什么目的? Changing the current working directory in Java?或更改刚刚创建的流程的工作目录?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读