1

I read multiple answers regarding how to run the linux shell command using subprocess module in python. 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.

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. 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.

Thanks!

spectre
  • 113
  • 1
  • 9
  • Possible duplicate of [How do I pipe a subprocess call to a text file?](https://stackoverflow.com/questions/4856583/how-do-i-pipe-a-subprocess-call-to-a-text-file) – user202729 Apr 13 '18 at 08:48

3 Answers3

2
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()
iBug
  • 35,554
  • 7
  • 89
  • 134
1

have you tried the os.system?

os.system("gnome-terminal -e 'your command'")
0
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.

spectre
  • 113
  • 1
  • 9