How to get all processes to a string? - python

There is the following code, how to display all processes in it with one line and remove from each .exe?
import psutil
for proc in psutil.process_iter():
name = proc.name()
print(name)
to get it
chrome, opera, svhost, ...

To get them in one line, use sep parameter in print function:
import psutil
enlisted = [proc.name() for proc in psutil.process_iter()]
print(*enlisted, sep = ' ')
Or there is end parameter too.

import psutil
procs = [proc.name().replace('.exe', '') for proc in psutil.process_iter()]
print(', '.join(procs))
As mentioned by #Vicrobot, the print line could as well be replaced by
print(*procs, sep = ', ')
while keeping in mind that the default seperator of print is already ' '.
.

Related

How to get which window manager is active using python?

I want to check which window manager is active using python? I used subprocess.run but it's giving me string type output like below :
name: xfwm4
class: xfwm4
pid: 6981
I just want xfwm4 from name.Is there any alternative of subprocess and wmctrl for showing window manager? This is my code so far,
def getWM():
try:
output = subprocess.run(['wmctrl', '-m'], text=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if output.stdout:
s = (output.stdout) + ' '
return s
except:
return None
Using split is simplest:
import subprocess as sb
output=sb.run(['wmctrl', '-m'], text=True,stdout=sb.PIPE, stderr=sb.PIPE)
namestr=output.stdout.split('\n')[0]
# For me this gives 'Name: KWin'
name=namestr.split(' ')[1]
# and this gives 'KWin'

illegal base64 data at input byte 6

So , i'm passing my parameters(a list and a string) to a perl file from my python file using subprocess , but it throws me a error.
The python code
import os
import subprocess
method = "operation"
data = ['param1', ' ', 'param2', 'LJs+p7l2KmzFWfhRxqAabcHWPHEGq2couwzktlfbpjwDoXb2GrWUGhrDwM3lwyFSK9R9rf6IAAE8szYVn3jBkQ==', ' ', ' ', 'filter_default', 'filter_default', 'filter_default',0,0]
proc = subprocess.Popen("perl"+" "+"file1.pl "+method+" " + " ".join([str(x) for x in data]),shell=True,stdout=subprocess.PIPE)
out,err = proc.communicate()
and while compiling it return's me this
illegal base64 data at input byte 6\n
Any quick fix for this?
There's nothing wrong with your base64 data. My guess is your Perl script is trying to decode "filter_default", where byte 6 IS invalid base64.
I notice you have spaces in your data list, but you are creating the command as one long string. That isn't going to be seen as blank parameters. You'll send
perl file1.pl operation param1 param2 lJs+p... filter_default filter_default
and the spaces won't be seen. If you really need to send empty parameters, then just send a list to Popen:
import os
import subprocess
method = "operation"
data = ['param1', ' ', 'param2', 'LJs+p7l2KmzFWfhRxqAabcHWPHEGq2couwzktlfbpjwDoXb2GrWUGhrDwM3lwyFSK9R9rf6IAAE8szYVn3jBkQ==', ' ', ' ', 'filter_default', 'filter_default', 'filter_default']
proc = subprocess.Popen( ["perl", "file1.pl", method] + data,shell=True,stdout=subprocess.PIPE)
out,err = proc.communicate()

Python subprocess: capture output of ffmpeg and run regular expression against it

I have the following code
import subprocess
import re
from itertools import *
command = ['ffprobe', '-i', '/media/some_file.mp4']
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
text = p.stderr.read()
retcode = p.wait()
text = text.decode('utf-8')
p = re.compile("Duration(.*)")
num = 0 #for debugging
for line in iter(text.splitlines()):
print(str(num) + line) #for debugging
m = p.match(str(line))
if m != None:
print(m.group(1))
When I look at the output there is a line that says "Duration" on it, however it is not captured, print(m.group(1)) is never reached. If I change the text variable to a hardcoded string of "Duration blahblah" I get " blahblah", which is what I expect. It seems like the regex doesn't recognize the text coming back from stderr. How can I get the text into a format that the regex will recognize and match on?
I have come up with the following solution, should it help anyone else attempting to capture duration from ffmpeg using python
import subprocess
import re
command = ['ffprobe', '-i', '/media/some_file.mp4']
p = subprocess.Popen(command, stderr=subprocess.PIPE)
text = p.stderr.read()
retcode = p.wait()
text = text.decode('utf-8')
p = re.compile(".*Duration:\s([0-9:\.]*),", re.MULTILINE|re.DOTALL)
m = p.match(text)
print(m.group(1))
p = re.compile(r".*?Duration(.*)")
Try this.match starts from the begining while there may might be something before duration.

Python scp copy file with spaces in filename

I'm trying to copy files in local network with scp.
It's working well with filenames without spaces, but it crash with.
I've tried to replace " " with "\ " as this exemple, but it don't work.
Here is my code:
def connection(locals):
a = (int(re.search(br'(\d+)%$', locals['child'].after).group(1)))
print a
perc = (Decimal(a)/100)
print (type(perc)), perc
while gtk.events_pending():
gtk.main_iteration()
FileCopy.pbar.set_text("Copy of the file in the Pi... " + str(a) + "%")
while gtk.events_pending():
gtk.main_iteration()
FileCopy.pbar.set_fraction(perc)
file_pc = "/home/guillaume/folder/a very large name of file with space .smthg"
file_pi = "pi#192.168.X.X:/home/pi/folder/a very large name of file with space .smthg"
if " " in file_pc:
file_pc = fichier_pc.replace(" ", '\\\ ') # tried '\\ ' or '\ '
file_pi = fichier_pi.replace(" ", '\\\ ') # but no way
else:
pass
command = "scp %s %s" % tuple(map(pipes.quote, [file_pc, file_pi]))
pexpect.run(command, events={r'\d+%': connection}) # this command is using to get the %
How can I fix this problem ?
Thanks
Use subprocess module and/or shlex.split():
import subprocess
subprocess.call(['scp', file_pc, file_pi])
and you don't need to worry about escaping or quoting anything
You may keep local file file_pc as is (pipes.quote will escape the spaces). The remote file should be changed:
import pipes
file_pi = 'pi#192.168.X.X:/home/pi/folder/file with space.smth'
host, colon, path = file_pi.partition(':')
assert colon
file_pi = host + colon + pipes.quote(path)
i.e., user#host:/path/with space should be changed to user#host:'/path/with space'
You might want to look into fabric, a Python library that streamlines the use of SSH.
from fabric.state import env
from fabric.operations import get
env.user = 'username'
env.key_filename = '/path/to/ssh-key'
get('/remote_path/*', 'local_path/')

Pass python script output to another programs stdin

I have an application that takes input, either from the terminal directly or I can use a pipe to pass the output of another program into the stdin of this one. What I am trying to do is use python to generate the output so it's formatted correctly and pass that to the stdin of this program all from the same script. Here is the code:
#!/usr/bin/python
import os
import subprocess
import plistlib
import sys
def appScan():
os.system("system_profiler -xml SPApplicationsDataType > apps.xml")
appList = plistlib.readPlist("apps.xml")
sys.stdout.write( "Mac_App_List\n"
"Delimiters=\"^\"\n"
"string50 string50\n"
"Name^Version\n")
appDict = appList[0]['_items']
for x in appDict:
if 'version' in x:
print x['_name'] + "^" + x['version'] + "^"
else:
print x['_name'] + "^" + "no version found" + "^"
proc = subprocess.Popen(["/opt/altiris/notification/inventory/lib/helpers/aex- sendcustominv","-t","-"], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
proc.communicate(input=appScan())
For some reason this subprocess I am calling doesn't like what is coming into stdin. However if I remove the subprocess items and just have the script print to stdout and then call the script from the terminal (python appScan.py | aex-sendcustominv), aex-sendcustominv is able to accept the input just fine. Is there any way to take a functions output in python and send it to the stdin of an subprocess?
The problem is that appScan() only prints to stdout; appScan() returns None, so proc.communicate(input=appScan()) is equivalent to proc.communicate(input=None). You need appScan to return a string.
Try this (not tested):
def appScan():
os.system("system_profiler -xml SPApplicationsDataType > apps.xml")
appList = plistlib.readPlist("apps.xml")
output_str = 'Delimiters="^"\nstring50 string50\nName^Version\n'
appDict = appList[0]['_items']
for x in appDict:
if 'version' in x:
output_str = output_str + x['_name'] + "^" + x['version'] + "^"
else:
output_str = output_str + x['_name'] + "^" + "no version found" + "^"
return output_str
proc = subprocess.Popen(["/opt/altiris/notification/inventory/lib/helpers/aex- sendcustominv","-t","-"], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
proc.communicate(input=appScan())

Categories

Resources