Reputation: 113
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!
Upvotes: 1
Views: 3078
Reputation: 113
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.
Upvotes: 0
Reputation: 37217
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()
Upvotes: 2
Reputation: 59
have you tried the os.system?
os.system("gnome-terminal -e 'your command'")
Upvotes: 1