gpt4 book ai didi

shell - 终端 cd 命令不适用于 Scala 脚本

转载 作者:行者123 更新时间:2023-12-04 17:54:35 26 4
gpt4 key购买 nike

我需要从 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?或者更改您刚刚创建的进程的工作目录?

关于shell - 终端 cd 命令不适用于 Scala 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10606808/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com