简体   繁体   English

如何在新终端中的python中运行linux终端命令

[英]How to run linux terminal command in python in new terminal

I read multiple answers regarding how to run the linux shell command using subprocess module in python.我阅读了有关如何在 python 中使用 subprocess 模块运行 linux shell 命令的多个答案。 In my case, i need to run linux shell commands inside my python code in such a way that these commands should get executed in new terminal.就我而言,我需要在我的 python 代码中运行 linux shell 命令,以便这些命令应该在新终端中执行。

subprocess.call(["df","-h"] 

I'm running say xyz.py in base terminal, when i execute above command, it overwrites on the output of xyz.py in the same terminal.我在基本终端中运行说 xyz.py,当我执行上述命令时,它会覆盖同一终端中 xyz.py 的输出。 I want this command to be executed in different terminal, or i want to store output of this command in a text file.我希望这个命令在不同的终端中执行,或者我想把这个命令的输出存储在一个文本文件中。

subprocess.call(["df","-h",">","somefile.txt"])

Above command is not working.上面的命令不起作用。

Edit-1: If i save the output in a text file, i also have to display it through python. Edit-1:如果我将输出保存在文本文件中,我还必须通过 python 显示它。

Thanks!谢谢!

import subprocess
fp = open("somefile.txt", "w")
subprocess.run(["df", "-h"], stdout=fp)
fp.close

Use a file handle.使用文件句柄。

If you want to print the output while saving it:如果要在保存时打印输出:

import subprocess
cp = subprocess.run(["df", "-h"], stdout=subprocess.PIPE)
print(cp.stdout)
fp = open("somefile.txt", "w")
print(cp.stdout, file=fp)
fp.close()

你试过 os.system 吗?

os.system("gnome-terminal -e 'your command'")
file = open("somefile.txt", "w")
subprocess.run(["df","-h"], stdout = file)
os.system("gnome-terminal -e 'gedit somefile.txt' ")

Above code is working.上面的代码正在工作。 If there are any simple/efficient way to do the same it'll be helpful.如果有任何简单/有效的方法可以做到这一点,那将会很有帮助。

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

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