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!

1

3 Answers 3

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()
Sign up to request clarification or add additional context in comments.

12 Comments

Thanks. It's working. Problem is, if i save it in a text file, i also have to display it using python.
@spectre You can use stdout=subprocess.PIPE to get the stdout, print it and then save it to the file.
Even before running the code, it shows error with "print(cp.out, file=fp)" line.
@spectre It's a typo. Fixed now.
Still it shows same error. Can you please check once and edit it. Thanks.
|
1

have you tried the os.system?

os.system("gnome-terminal -e 'your command'")

5 Comments

Thanks. Problem with this is, new terminal is getting opened. But it's unable to execute the command inside new terminal
And what about creating a child with os.fork?
os.system(" gnome-terminal -e '['df','-h']' ") This is what i did. What corrections do you suggest?
I think this works fine, but if you want you can try fork to create a child (new process). See this: stackoverflow.com/questions/33560802/pythonhow-os-fork-works
The correct syntax is os.system("gnome-terminal -e 'df -h'") or better subprocess.run(["gnome-terminal", "-e", "df -h"])
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.