Search code examples
pythonbashsubprocess

top command working in console but not while using Python subprocess


I want to use specific top command and save the results to file. Using it in console works fine, but when trying the same in python with subprocess it shows an error. I'm using Linux Fedora 41.

Using this command in console outputs results i want, while saving to file:

top -b -n 1000 -d 1 -p `pgrep Discord | tr "\\n" "," | sed 's/,$//'` > test.txt

but when using it in python program with subprocess:

import subprocess

bashCommand = """ top -b -n 1000 -d 1 -p `pgrep Discord | tr "\\n" "," | sed 's/,$//'` """

print(bashCommand)

with open("test.txt", "w") as outfile:
    proces = subprocess.call(bashCommand, shell=True, stdout=outfile)

it throws:

top: option requires an argument -- 'p'

Why is that and how to fix it?

Process Discord is open, I tried the same with firefox and others to no avail.


Solution

  • Worked out the issue, flatpak pycharm was running in a sandbox. My bad.