繁体   English   中英

在新打开的终端中运行命令

[英]Run commands in newly opened terminal

我想通过python打开一个新终端。 在那个新生成的终端中,我想执行命令。 我检查了多个通过类似问题提出的帖子,但我找不到答案。

我试过这个:

import os
    
os.system("gnome-terminal -e 'cd /home/john/Documents; echo 'writing to file' > testfile.txt'")

新终端生成,但命令不会在新终端中执行。

❯ python3 TestOpenTerminal.py 
# Option “-e” is deprecated and might be removed in a later version of gnome-terminal.
# Use “-- ” to terminate the options and put the command line to execute after it.
# Error: Failed to execute child process “cd” (No such file or directory)

我怎样才能做到这一点? 谢谢

cd命令不适用于 gnome-terminal 命令,您需要使用选项--working-directory=/path/to/dir
-e选项已弃用,您需要使用--后跟命令,如gnome-terminal -- 'command'
要操作文件,我可以使用的唯一方法是在命令之前使用bash和选项-c
所以你想要做的命令是:

gnome-terminal --working-directory=/home/john/Documents -- bash -c "echo 'writing to file' > testfile.txt"

我真的建议您使用结构库来使用终端命令,它适用于所有系统并将 output 返回给您。

我不知道你是否真的想打开一个终端,但你可以通过 python 打开文件并用它写。 尝试使用 open() 和 write() 函数。

仔细看看你的命令。 您的开头单引号被“写入文件”周围的单引号关闭,这会导致混乱。

os.system("gnome-terminal -e 'cd /home/john/Documents; echo 'writing to file' > testfile.txt'")

此外,gnome-terminal 的默认行为是在完成时关闭。 您可以通过如下编辑配置文件来使其保持打开状态...

在 gnome-terminal 中,go 到 Edit -> Profile Preferences -> Title。 单击命令选项卡。 Select 从标有“命令退出时”的下拉菜单中按住终端。 您应该为此创建一个新配置文件并执行

gnome-terminal --window-with-profile=NAMEOFTHEPROFILE -e 命令

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM