final="cacls " + "E:/" + "\"" + list1[2] + " " + list1[3] + "\"" + " /p " + str
pro = subprocess.Popen(final,shell=True, stdin=subprocess.PIPE)
pro.communicate(bytes("Y\r\n",'utf-8'))
Trying to set permission to a folder Using Python but while running this command , User input needs to be provided too i.e
it asks ARE YOU SURE(Y/N) and the user needs to enter "Y" or "N"
The above code is not setting the permission.
This was the question i had asked before:
Python code to send command through command line
As a smart programmer, use PBS
Then, the code is:
from pbs import type as echo# Isn't it echo for Windows? If not, use the correct one
script = Command("/path/to/cacls ")
print script(echo("Y"), ("E:/" + "\"" + list1[2] + " " + list1[3] + "\"" + " /p " + str).split())
Related
This question already has answers here:
How do I print colored text to the terminal?
(64 answers)
Closed 1 year ago.
as maybe some of you know and regarding to shell scripts - tput is utility uses the terminfo database to make the values of terminal-dependent capabilities and information available to the shell
in my python script I have the following example: ( just a sample from long code )
for TOPIC in list:
if str(val) in TOPIC:
word = TOPIC.split()[1]
print ("Topic " + word + " is successfully configured")
else:
try:
word = TOPIC.split()[1]
print ("Topic " + word + " bad configuration")
except IndexError:
pass
I want to change the color from white to green on the following printing:
print ("Topic " + word + " is successfully configured")
or to change the color from white to red on:
print ("Topic " + word + " bad configuration")
is it possible to change the color in python3 as we did for example in bash scripts?
import os
os.system("")
RED = "\x1B["
GREEN = '\033[32m'
word = "random_topic_name"
print(GREEN+"Topic " + word + "successfully configured" )
print(RED+"Topic " + word + "bad configuration" )
I am trying to complete this part of my program. In this section, I am trying to speed up or slow down a video based on a factor variable. Once it's done, I use moviepy to turn it into a VideoFileClip, then I delete the file.
if factor <= 2:
system("ffmpeg -i " + paths[dex] + " -vf setpts=" + str(vfactor) + "*PTS -an ./Media/Videos/temp.mp4")
system("ffmpeg -i " + paths[dex] + " -filter:a atempo=" + str(factor) + " -vn ./Media/ShortSounds/temp.mp3")
elif 2 < factor < 4:
factor = round(sqrt(factor), 1)
system("ffmpeg -i " + paths[dex] + " -vf setpts=" + str(vfactor) + "*PTS,setpts=" + str(vfactor) + "*PTS -an ./Media/Videos/temp.mp4")
system("ffmpeg -i " + paths[dex] + " -filter:a atempo=" + str(factor) + ",atempo=" + str(factor) + " -vn ./Media/ShortSounds/temp.mp3")
elif factor > 4:
raise Exception("File " + paths[dex] + " is too long.")
t = VideoFileClip("./Media/Videos/temp.mp4")
t.audio = AudioFileClip("./Media/Videos/temp.mp3")
templist.append(t)
remove("./Media/Videos/temp.mp4")
However, when the code gets to the deletion command, it has the following error:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: './Media/Videos/temp.mp4'
What's strange is, I can see the temp.mp4 file, and it runs just fine. I never get this error while manually running the temp.mp4 file.
I have tried the following:
Waiting 5, 10, and 20 seconds before deleting the file.
Running "taskkill -f -im ffmpeg.exe" before deleting the file
I went through the debugger, and right before the deletion, I checked in task manager to see if ffmpeg was still running, and it wasn't.
Do you guys have any idea what could be holding this up? My code worked previously when I was trying to just do audio, but I am trying it with video and this is happening.
I'm writing due to an error I just cannot seem to work around.
WASX7017E: Exception received while running file "/root/wsDeploy.py"; exception information: com.ibm.ws.scripting.ScriptingException: WASX7115E: Cannot read input file "/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/installableApps/my_ear_file.ear,'[-node DefaultNode01 -cell DefaultCell01 -server server1 -MapWebModToVH [[ "Our War One" first_war.war,WEB-INF/web.xml default_host ]["Our War Two" second_war.war,WEB-INF/web.xml default_host]["Our War Three" third_war.war,WEB-INF/web.xml default_host]]]'"
Now that script has the following variables and syntax:
ParameterStr = "-node DefaultNode01 -cell DefaultCell01 -server server1 -MapWebModToVH [[ \"Our War One\" first_war.war,WEB-INF/web.xml default_host ][\"Our War Two\" second_war.war,WEB-INF/web.xml default_host][\"Our War Three\" third_war.war,WEB-INF/web.xml default_host]]"
EAR_FILE=/path/to/file/my_ear_file.ear
This is the portion of code which is choking when executed by websphere in jython(2.7) (Also fails in 2.1)
elif UpdateExistingorNewApp == "INITIAL" and ConditionForUpdate == 0:
AdminApp.install(EAR_FILE + "," + "'" + "[" + ParameterStr + "]" + "'")
AdminConfig.save()
I have tried
AdminApp.install( 'EAR_FILE' + "," + "'" + "[" + ParameterStr + "]" + "'")
AdminApp.install( "'" + EAR_FILE + "'" +"," + "'" + "[" + ParameterStr + "]" + "'")
AdminApp.install( \' EAR_FILE \' + "," + "'" + "[" + ParameterStr + "]" + "'")
I have even tried adding the "[ ]" pair inside the ParameterStr variables as well.
I have looked at the following documents for guidance:
https://www.ibm.com/developerworks/community/forums/html/topic?id=43cee700-9074-49e1-9223-7c4db2d89680
https://developer.ibm.com/answers/questions/258458/ucd-install-application-fails-with-wasx7115e-canno/
I have verified the path to the ear, the permissions on the ear, and the ownership of the ear.
Am I having an issue similar to globbing? The input file is there, and is world readable. I have even run the script from the same location as the (installableApps) folder for the AppSrv01 Profile.
Any help would be highly appreciated.
EDIT:
So it we're past this part now. So I imagine that I will need to start escaping any meta characters. I'm posting what a fully constructed argument looks like:
AdminApp.install('/opt/IBM/WebSphere/AppServer/installableApps/my_ear_file.ear','[-node DefaultNode01 -cell DefaultCell01 -server server1 -MapWebModToVH [[ \"Our War One\" first_war.war,WEB-INF/web.xml default_host ][\"Our War Two\" second_war.war,WEB-INF/web.xml default_host][\"Our War Three\" third_war.war,WEB-INF/web.xml default_host]]]')
Our argument is slightly different at this time, but that appears to still be acceptable to the interpreter
AdminApp.install( /opt/IBM/WebSphere/AppServer/installableApps/my_ear_file.ear,'[-node DefaultNode01 -cell DefaultCell01 -server server1 -MapWebModToVH [[ \"Our War One\" first_war.war,WEB-INF/web.xml default_host ][\"Our War Two\" second_war.war,WEB-INF/web.xml default_host][\"Our War Three\" third_war.war,WEB-INF/web.xml default_host]]]')
So that generates a
java.lang.IllegalArgumentException: java.lang.IllegalArgumentException: WASX7122E: Expected "-" not found.
So I am now trying to see which meta characters I can deal with via trial and errors.
I am basing this off of the comment response by kgibm.
You're concatenating the ear file name with the options, whereas those are two parameters separated by a comma. Try:
AdminApp.install(EAR_FILE, "'" + "[" + ParameterStr + "]" + "'")
EDIT 1 - added more code
I'm not sure that proc.communicate was needed, it was one of the suggestions I found from some other stackoverflow code.(Sorry I was tired last night and didn't think too much before asking the question.)
I should add that I am not an experienced coder (mechanical engineer) as you can probably tell from my code
In my Gui I have a button to call a subprocess
The subprocess (screenshot-cmd.exe) creates a png of a cropped screen shot but it won't actually produce the file until there is an error or if the button click event is over.
This makes me think that the subprocess is not actually run until the event is finished
I want to call the process several times after a single button press and move the files that it produces after each one is produced
if I use proc.wait(), the process hangs indefinitely.
How do I stop this?
# function to take a single image called 'fileName' and place it in directory 'dir'
def takeImage(dir,fileName):
# calculate the view to capture to get the whole display window in.
clientRect = win32gui.GetClientRect(win32gui.GetForegroundWindow())
windowRect = win32gui.GetWindowRect(win32gui.GetForegroundWindow())
print(windowRect)
windowSize = [windowRect[2]-windowRect[0],windowRect[3]-windowRect[1]]
print(windowSize)
print(clientRect)
diffSize = [windowSize[0] -clientRect[2], windowSize[1] - clientRect[3]]
lrbBorder = diffSize[0]/2
topBorder = diffSize[1] - lrbBorder
print("sizeDiff = " + str(diffSize))
windowName = win32gui.GetWindowText(win32gui.GetForegroundWindow())
handleId = win32gui.GetForegroundWindow()
leftMar = designLabel.GetPosition()[0] + lrbBorder
topMar = designLabel.GetPosition()[1] + topBorder + designLabel.GetSize()[1]
rightMar = leftMar + scene.width
bottMar = topMar+scene.height
margins = [leftMar,topMar,rightMar,bottMar]
print(margins)
# now print the view.
#command_line = r"screenshot-cmd -wt '" + windowName + "' -rc " + str(margins[0]) + " " + str(margins[1]) + " " + str(margins[2]) + " " + str(margins[3]) + " -o " + fileName
command_line = r"screenshot-cmd -wt '" + windowName + "' -rc " + str(margins[0]) + " " + str(margins[1]) + " " + str(margins[2]) + " " + str(margins[3]) + " -o " + fileName
print(command_line)
args = shlex.split(command_line)
proc = subprocess.Popen(args)
proc.wait()
wx.Yield()
if not os.path.isdir(dir):
os.makedirs(dir)
newPath = os.path.join(dir,fileName)
if os.path.exists(newPath):
os.remove(newPath)
oldPath = os.path.join(os.getcwd(), fileName)
print("Old Path: " + oldPath)
print("Exists: " + str(os.path.exists(oldPath)))
shutil.move(oldPath,newPath)
return
#event called upon clicking 'takeTenImag' button
def takeTenImgE(evt):
global designNo
global workingDirectory
global numDesigns
fileNameRoot = "test_"
fileExtention = ".png"
# check there are at least 10 designs
if numDesigns > 9 and os.path.exists(workingDirectory):
# find directory path to put images in
dir = os.path.join(workingDirectory, "images")
# for each design
for x in range(10):
print("design =" + str(designNo))
fileName = fileNameRoot + str(designNo) + fileExtention
print("------------------")
print("for x = " + str(x) + " " + fileName)
# create image and save
print(dir)
takeImage(dir,fileName)
#move to next design
wx.PostEvent(forwardDesign, wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, forwardDesign.GetId()) )
wx.Yield()
print("design =" + str(designNo))
return
takeTenImg = wx.Button(p, label='Take Ten Images', pos=(rb + visScaleText.GetSize()[0]+10,takeImg.GetPosition()[1]+5 +takeImg.GetSize()[1]), size = (100,30))
takeTenImg.Bind(wx.EVT_BUTTON, takeTenImgE)
https://code.google.com/p/screenshot-cmd/
Barnaby, you may be over-complicating your subprocess use. Popen is typically used for when you need to communicate with the process during the time it is running. From the sound of it, you don't need to do that, so might want to use a higher level function. See the docs on subprocess' various invocations, and perhaps try using the call method. You'll need shell=True, as detailed in SO questions such as this one.
I've found that the error is in my calling of subprocess.
I was using:
command_line = r"screenshot-cmd -wt '" + windowName + ...."
args = shlex.split(command_line)
subprocess.call(args,shell=True)
changing this to:
command_line = r"screenshot-cmd -wt '" + windowName + ...."
subprocess.call(command_line,shell=True)
solves the hang.
What is peculiar is that both options work when not inside a wx button click event(i.e. a python script launched from the command line), but only the second works when inside the wx button click event.
If anyone could enlighten me why that would be most appreciated.
EDIT:
upon further investigation, the hang is caused by trying to specify the active window in screenshot-cmd.
To solve this I find the position of the window using
windowRect = win32gui.GetWindowRect(win32gui.GetForegroundWindow())
and then use screenshot-cmd without specifying a window.
This solves all issues although it is unclear why this causes problems
final="cacls " + "E:/" + "\"" + list1[2] + " " + list1[3] + "\"" + " /p " + str
os.system(final)
I am trying to set permission to a folder Using Python but while running this command , User input needs to be provided too i.e
it asks ARE YOU SURE(Y/N) and the user needs to enter "Y" or "N"
Is there any way to use python to send the user input "Y" along with the above code?
pro = subprocess.Popen(final,shell=True, stdin=subprocess.PIPE)
pro.communicate(bytes("Y\r\n",'utf-8'))
I have added the following code . The program exits without setting the permission.
http://jimmyg.org/blog/2009/working-with-python-subprocess.html#writing-to-standard-input
Try using the subprocess module
import subprocess
cmd = ["cacls", "E:/" + list1[2], list1[3], "/p", str]
pro = subprocess.Popen(final, stdin=subprocess.PIPE)
pro.communicate("y\r\n")
As a smart programmer, use PBS
Then, the code is:
from pbs import type as echo# Isn't it echo for Windows? If not, use the correct one
script = Command("/path/to/cacls ")
print script(echo("Y"), ("E:/" + "\"" + list1[2] + " " + list1[3] + "\"" + " /p " + str).split())