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'
Related
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 ' '.
.
I need to get size of the window in Python and assign it to the variable. I'm trying with this:
windowSize = '''
tell application "System Events" to tell application process "%(app)s"
get size of window 1
end tell
''' % {'app': app} // app = "Terminal
(wSize, error) = Popen(['osascript', '/Setup.scpt'], stdout=PIPE).communicate()
print("Window size is: " + wSize)
I get this error only: TypeError: can only concatenate str (not "bytes") to str
I'm completely new to Python so I hope you can help me with it
You'll need to pass your AppleScript (i.e. windowSize) as input to Popen.communicate():
Example:
from subprocess import Popen, PIPE
app = "Terminal"
windowSize = '''
tell application "%(app)s"
get size of window 1
end tell
''' % {'app': app}
proc = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True)
wSize, error = proc.communicate(windowSize)
print("Window size is: " + wSize)
Notes:
In your windowSize AppleScript it shouldn't be necessary to tell application "System Events" to tell ... - you can just tell application "%(app)s" instead. However, you're AppleScript still works assuming Access for assistive devices is enabled in System Preferences.
This will log something like the following to the console:
Window size is: 487, 338
You may want to consider utilizing str.replace() in your print statement to replace the comma (,) with an x. For instance, changing print statement in the gist above to this:
print("Window size is: " + wSize.replace(",", " x"))
will print something like this instead:
Window size is: 487 x 338
If you wanted to replace the two lines of code in the gist above which begin with proc and wSize) with one line (similar to your OP) then replace them with the following instead:
(wSize, error) = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True).communicate(windowSize)
To get the windows width and height as two separate variables you could subsequently utilize the str.split() method to split the wSize variable (using the string ", " as the delimiter). For instance:
# ...
wWidth = wSize.split(", ")[0]
wHeight = wSize.split(", ")[1]
print("Window width is: " + wWidth)
print("Window height is: " + wHeight)
Here is my attempt to simplify a process of preparing working environment. Assume your team has many Gitolite hosted repositories and you want to:
get full list of them;
clone some of them as simple and fast as can.
This script allows it. So, the answers for above questions are:
Show gitolite repos:
ssh git#server_ip
And the following code for cloning:
#!/usr/bin/python
import subprocess
import sys
import os
import re
FILTER = None
# check shell arguments
if len(sys.argv) == 2:
FILTER = sys.argv[1]
GIT_PATH = "git#server_ip"
# run system command and retrieve result
p = subprocess.Popen("ssh " + GIT_PATH, stdout=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
output = re.sub(r'^[\S\s]*?(?=web/)', '', output)
output = re.sub(r'R|W', '', output)
output = output.split()
# filter function
def f(line):
if line.find(FILTER) != -1:
return True
return False
if FILTER:
output = filter(f, output)
yes = 'yes'
no = 'no'
for line in output:
print(line)
choice = input("Do you want to clone this repo (yes/no): ")
if choice == yes:
os.system("git clone " + GIT_PATH + ':/' + line.strip())
print('Done!')
print('All work is done! Congrats!')
Syntax: python clone.py [filter]
Filter, when specified, allows to get only repos that contain filter string as substring.
Suggestions for improvement are welcome! Thanks.
I am using vb.net and Arcobjects for my program. I am creating a button for ArcMap 10 that will convert a kml to a lyr file.
I am having problems passing variables into the python code. The variables are file paths and it works great if I hard code them in with / instead of . When the variables are dynamically passed in, the program breaks at the "/"s in the path names:
Dim Filelocation As OpenFileDialog = New OpenFileDialog()
Filelocation.Title = "Please point photo of the owner"
Filelocation.InitialDirectory = "B:\GeoSpatialData\Projects\004402 Griffiths\File Structure\Geospatial\GPS\KML"
If Filelocation.ShowDialog = DialogResult.OK Then
Dim kmlFile As String
kmlFile = Filelocation.FileName
Dim args As String
args = kmlFile & " " & kmlFile.Substring(0, kmlFile.LastIndexOf("\")) & " test"
Dim args2 As String = args.Replace("\", "/")
Dim procStartInfo As System.Diagnostics.ProcessStartInfo = New System.Diagnostics.ProcessStartInfo("C:\Python26\python", "C:\Users\KJacobsen\kml_to_shp.py " & args2)
' The following commands are needed to redirect the standard output.
' This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = True
procStartInfo.UseShellExecute = False
' Do not create the black window.
procStartInfo.CreateNoWindow = False
' Now you create a process, assign its ProcessStartInfo, and start it.
Dim proc As New System.Diagnostics.Process()
proc.StartInfo = procStartInfo
proc.Start()
proc.WaitForExit()
' Get the output into a string.
Dim result As String = proc.StandardOutput.ReadToEnd()
' Display the command output.
Console.WriteLine(result)
End If
Catch objException As Exception
' Log the exception and errors.
Console.WriteLine(objException.Message)
End Try
My python script looks like this:
import os
import arcpy
import sys
import glob
arcpy.KMLToLayer_conversion(sys.argv[1],sys.argv[2],sys.argv[3])
print
The path returned contains spaces? It seems so from your initial directory.
In that case the command arguments passed to the script could be wrong.
Try to enclose everything in double quotes and avoid direct manipulation of paths.
Use Path.GetDirectoryName() instead
Dim args As String
args = """" + kmlFile + """ "
args = args & """" & Path.GetDirectoryName(kmlFile) & """ test"
Replace "\" to "\\\"
Does it work?
I have created a string from
connectString = 'D:\Database\10.2.0\BIN\sqlplus.exe -L sys/PASSWORD'
output = str(call(connectstring))
this results from print output
stuff stuff stuff
stuff even more stuff
ORA-28009
stuff stuff
stuff and stuff
I do
output.find('ORA-28009')
but it does not find the string sequence. The only reason I can think of is because the string is multi line. How do I handle this?
try to normalise the string removing the special charachter.
i use a function like this:
def trim (str):
str = str.replace(' ', '')
str = str.replace('\s', '')
str = str.replace('\t', '')
str = str.replace('\r', '')
str = str.replace('\n', '')
return str
Maybe you can adapt it to your case.
best,
Ste
Try replacing
output = str(call(connectstring))
with
output = str(check_output(connectstring))
which returns the bytes from the output of the command.
This is what I did to solve it. The sPath variable is needed because I have two seperate instances of Oracle on the same server. To properly test the sys account password I needed to run the sqlplus contained in the specific dir with the correct password for that instance.
def startSQLHelper(self, sPath, sPassword):
print '--starting SQL helper--'
args = [sPath + 'sqlplus.exe', '-L', 'sys/'+sPassword]
return subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def checkOraPass (self, sPath, sPassword):
print '--checkOraPass--'
p = self.startSQLHelper(sPath, sPassword)
output = p.communicate()[0]
print output
if output.find('ORA-28009') != -1:
print 'Password passed'
return True
return False