英文:
run `python.exe` to run the python shell interactively
问题
我正在尝试运行一个exec.Command
命令来交互式地运行Python shell。我该如何输入内容?
package main
import (
"fmt"
"os"
"os/exec"
"io"
"log"
)
func main() {
fmt.Println("Before Python shell:")
cmd := exec.Command("python.exe")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
_ = cmd.Run()
}
你可以使用cmd.Stdin
字段来输入内容。你可以通过创建一个io.WriteCloser
接口的管道来将输入内容传递给命令。例如,你可以使用io.Pipe()
函数创建一个管道,然后将管道的写入端口赋值给cmd.Stdin
字段。这样,你就可以通过写入管道来向Python shell发送输入。
以下是修改后的代码示例:
package main
import (
"fmt"
"os"
"os/exec"
"io"
"log"
)
func main() {
fmt.Println("Before Python shell:")
cmd := exec.Command("python.exe")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// 创建管道
pr, pw := io.Pipe()
defer pr.Close()
// 将管道的写入端口赋值给cmd.Stdin
cmd.Stdin = pr
// 启动命令
err := cmd.Start()
if err != nil {
log.Fatal(err)
}
// 向管道写入输入内容
_, err = io.WriteString(pw, "print('Hello, World!')")
if err != nil {
log.Fatal(err)
}
// 关闭管道的写入端口
pw.Close()
// 等待命令执行完成
err = cmd.Wait()
if err != nil {
log.Fatal(err)
}
}
这样,你就可以通过向管道写入内容来向Python shell发送输入。在上面的示例中,我向管道写入了print('Hello, World!')
,你可以根据需要修改输入内容。
英文:
I am trying to run a exec.Command python.exe
to run the python shell interactively. How can I type into it?
package main
import (
"fmt"
"os"
"os/exec"
"io"
"log"
)
func main() {
fmt.Println("Before Python shell:")
cmd := exec.Command("python.exe")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
_ = cmd.Run()
}
答案1
得分: 2
如果你的go
程序的标准输入和标准输出是终端,并且你将exec.Command
的标准输出和标准输入都设置为go
程序的标准输出和标准输入,那么你确实可以期望python
(在这种情况下)与终端进行交互,就像直接执行一样。
这段代码:
package main
import(
"os"
"os/exec"
)
func main() {
cmd := exec.Command("python3")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
panic(err)
}
}
具有以下行为:
% go run t.go
Python 3.9.6 (default, Aug 5 2022, 15:21:02)
[Clang 14.0.0 (clang-1400.0.29.102)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print("hello world")
hello world
>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> ^D
[2023/04/22 11:31:20 CDT ] ~
你的代码缺少了cmd.Stdin = os.Stdin
这一行。
英文:
If your go
program's stdin and stdout is a terminal, and you set your exec.Command
's stdout and stdin to the go
program's stdout and stdin, you can indeed expect python
(in this case) to interact with the terminal just like it was executed directly.
This code:
package main
import(
"os"
"os/exec"
)
func main() {
cmd := exec.Command("python3")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
panic(err)
}
}
Has this behavior:
% go run t.go
Python 3.9.6 (default, Aug 5 2022, 15:21:02)
[Clang 14.0.0 (clang-1400.0.29.102)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print("hello world")
hello world
>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> ^D
[2023/04/22 11:31:20 CDT ] ~
Your code was missing cmd.Stdin = os.Stdin
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论