Python script won't execute batch file in IIS 7.5 - python

I have a python script that automates Erdas image processing software based on parameters gathered by the script from the image metadata. The python script gathers these parameters into list which gets written to a batch file, and then runs the batch file, which tells the Erdas software to process the images. When I run this outside of the IIS directory, the script works perfectly. However, when I run the script within the IIS directory, the script partially runs, but gives me an error message when it tries to run the batch file. Just an FYI, I've searched everywhere for a solution to this problem. I've tried changing folder and file permissions and IIS manager settings with no luck. Here is the error message:
Traceback (most recent call last):
File "python_page.py", line 1018, in <module>
main()
File "python_page.py", line 1002, in main
getAtmCorrectBatchFile(AtmCorrectBatchlist)
File "python_page.py", line 912, in getAtmCorrectBatchFile
f = open(basePath + '/atm_batch_process.bat', 'w')
IOError: [Errno 13] Permission denied: 'C:/inetpub/wwwroot/cgi-bin/atm_batch_process.bat'
Below is the code where the error is occurring. What I'm most confused about is that the error is located within the getAtmCorrectBatchFile() function that creates the batchfile, but the error arises when the script tries to call the RunAtmCorrectBatch() function listed directly below it. The script has successfully created the batch file and saved it in the cgi-bin directory at this point, so why would the error be within the function that creates the batch file instead of the one that tries to run the batch file?
Edit: I can right click the batch file within the cgi-bin directory and select run, which successfully outputs the processed images, just for some reason this doesn't work when the python script tries to run the batch file.
def getAtmCorrectBatchFile(batchlist):
f = open(basePath + '/atm_batch_process.bat', 'w') #line 912
for i in range (0, len(batchlist)):
f.write(str(batchlist[i]).replace('\\', '/') +'\n')
f.close()
def RunAtmCorrectBatch():
try:
from subprocess import Popen
p = Popen("/atm_batch_process.bat", cwd=basePath)
stdout, stderr = p.communicate()
except WindowsError:
pass

Related

GUI App shows File not found in directory Error

I made a GUI for a python program that allows me to read a csv file and display the data on the GUI. The GUI works perfectly fine when I run the program through IDLE. However when I try to run the program file as it is from Windows Explorer it shows the following error.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "C:\Python\gui1.py", line 43, in find_result
with open("RESULTS.csv") as a:
FileNotFoundError: [Errno 2] No such file or directory: 'RESULTS.csv'
This is the program code:
import tkinter as tk
import csv
root=tk.Tk()
root.title('Results')
tk.Label(root,text="Enter your Roll Number:").grid(row=1,column=1,sticky=tk.W)
tk.Label(root,text="Name:").grid(row=4,column=1,sticky=tk.W)
tk.Label(root,text="Total (Core 5 Subjects):").grid(row=5,column=1,sticky=tk.W)
tk.Label(root,text="Total (Best 5 Subjects):").grid(row=6,column=1,sticky=tk.W)
tk.Label(root,text="Percentage:").grid(row=7,column=1,sticky=tk.W)
tk.Label(root,text="Rank:").grid(row=8
,column=1,sticky=tk.W)
rno=tk.StringVar()
name_=tk.StringVar()
t1_=tk.StringVar()
t2_=tk.StringVar()
perc_=tk.StringVar()
rank_=tk.StringVar()
tk.Entry(root, textvariable=rno,justify=tk.RIGHT).grid(row=1,column=2,padx=3,pady=3)
def find_result():
tk.Label(root,textvariable=name_,justify=tk.RIGHT).grid(row=4,column=2,sticky=tk.E)
tk.Label(root,textvariable=t1_,justify=tk.RIGHT).grid(row=5,column=2,sticky=tk.E)
tk.Label(root,textvariable=t2_,justify=tk.RIGHT).grid(row=6,column=2,sticky=tk.E)
tk.Label(root,textvariable=perc_,justify=tk.RIGHT).grid(row=7,column=2,sticky=tk.E)
tk.Label(root,textvariable=rank_,justify=tk.RIGHT).grid(row=8,column=2,sticky=tk.E)
with open("RESULTS.csv") as a:
reader=csv.reader(a)
for i in reader:
if i!=[]:
if i[0]==rno.get():
name=i[1][2:]
t1=i[19]
t2=i[20]
perc=i[21]
rank=i[22]
name_.set(name)
t1_.set(t1)
t2_.set(t2)
perc_.set(perc)
rank_.set(rank)
tk.Button(root, text="Check your Result",command=find_result).grid(row=2,column=2)
root.mainloop()
Opening program with IDLE:
Opening program through Explorer:
open("RESULTS.csv") looks for that file in the current working directory, whatever that happens to be. This must be different for the two different ways you run the code. Do one of the following.
Give open an absolute path to the file instead of a relative one. If you know the location of the data file relative to the location of the program file, use __file__, which has the location of the program file, as the starting point. Note 1: that when working interactively, without running a file, __file__ does not exist. Note 2: If you do not understand 'absolute path', do a web search.
Explicitly set the current directory to the one containing the file with os.chdir(path). where path is absolute, not relative. This is more useful if opening several files in that directory.

Move file in Python with shutil that has just been changed

I wrote a Python script which calls subprocess which will create a file:
subprocess.run(["youtube-dl.exe", "-o " + fileName, link])
After that I'd like to move my file to a different directory:
shutil.copy("C:\\Users\\***\\Desktop\\m2.m4a", "C:\\Users\\***\\Desktop\\Songs\\m2.m4a")
But that gives me the following error:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\***\Desktop\m2.m4a'
But the file definitely exists. I tried to move a file which has not just been altered, and it works.
In case Windows needs time to create the file properly, I paused the code after the file creation and before the shutil.move-command:
time.sleep(4)
But it still doesn't work. Is it maybe because subprocess is still running and shutil can't access the file at the same time? Or because Python doesn't know that a new file has just been created? Thanks for your help!

Why is my script attempting to unzip files that haven't been downloaded yet?

I have a Python 3 script that I am writing to do three things:
1) Determine which Retrosheets data files are supposed to be downloaded
2) Create wget commands to retrieve the files and download them
3) Unzip the files after they have been downloaded.
When testing each function in the Python Console, I have no problems. But, when I try to do everything automatically, I get the following output:
Start Decade: 1930
End Decade: 1950
Creating wget commands...
Commands created...
Downloaded 3 files.
Unzipping files...
Traceback (most recent call last):
File "import_pbp.py", line 54, in <module>
unzip_data(decade_files)
File "import_pbp.py", line 39, in unzip_data
with zipfile.ZipFile('zip' + file, 'r') as zip_ref:
File "/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5 /lib/python3.5/zipfile.py", line 1009, in __init__
self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: 'zip1930seve.zip'
The files are downloaded after this output to the console. This would seem to indicate that the unzip function is running before the files are downloaded. How do I make sure that my files are downloaded before the unzip function is called? Code below:
Download function:
# define function to execute the download commands
def download_data(commands):
for command in commands:
os.popen(command)
print('Downloaded ' + str(len(commands)) + ' files.')
Unzip Function:
# Unzip the data files into the 'unparsed' folder.
def unzip_data(file_list):
print('Unzipping files...')
for file in file_list:
with zipfile.ZipFile('zip' + file, 'r') as zip_ref:
zip_ref.extractall('unparsed/')
print(file + ' unzipped')
print('All files unzipped...')
EDIT: I looked at the response in this thread but it didn't quite explain what I needed like tdelaney did below. They are similar, but for my purposes, different. Especially since that question is 6 years old and I'm guessing there may have been significant changes to the language since then.
EDIT 2: Removed non-essential code to shorten the post.
os.popen doesn't wait for the process to complete so you launch all of the commands at once then try the unzips before they are done. Since you don't read the stdout pipe returned from os.popen, you also risk the program hanging if the output pipe fills.
The subprocess module has several functions for calling programs. Assuming you really do want all of the commands to run in parallel and that you just want to discard any output data from the commands, you could reimplement that function as
import subprocess as subp
import os
# define function to execute the download commands and unzip
def download_data(commands):
procs = []
for command in commands:
procs.append(subp.Popen(command, shell=True,
stdout=open(os.devnull, 'wb')))
for proc in procs:
proc.wait()
print('Downloaded ' + str(len(commands)) + ' files.')

Error when creating directory and then opening a file within it in Python, but no error if directory already exists

I expect a directory to be created and then a file to be opened within it for writing to when I execute my code below in Python 2.6.6,
import subprocess
def create_output_dir(work_dir):
output_dir = '/work/m/maxwell9/some_name5/'
subprocess.Popen(['mkdir', output_dir])
return output_dir
if __name__ == '__main__':
work_dir = '/work/m/maxwell9/'
output_dir = create_output_dir(work_dir)
#output_dir = '/work/m/maxwell9/some_name5/'
filename = output_dir + 'bt.sh'
with open(filename, 'w') as script:
print('there')
but instead I get the error,
Traceback (most recent call last):
File "slurm_test.py", line 13, in <module>
with open(filename, 'w') as script:
IOError: [Errno 2] No such file or directory: '/work/m/maxwell9/some_name5/bt.sh'
If I run the script, I can then see that the directory is created. If I then uncomment the line,
#output_dir = '/work/m/maxwell9/some_name5/'
and comment the line,
output_dir = create_output_dir(work_dir)
then the file is output fine. So there is something about creating the folder and then writing to it in the same script that is causing an error.
subprocess.Popen starts up an external process but doesn't wait for it to complete unless you tell it to (e.g. by calling .wait on the returned Popen instance). Most likely, mkdir is in the process of creating a directory while open(filename, 'w') attempts to create a file in that directory. This is an example of a "race condition".
The solution is to .wait on the open process (as noted above), or you can use one of the convenience wrappers subprocess.check_output, subprocess.check_call or (even better), you can avoid subprocess entirely by using os.mkdir or os.makedirs.
You could use the os library instead of subprocess, which makes for a more straightforward implementation. Try swapping out your create_output_dir function with this:
import os
def create_output_dir(work_dir):
try:
os.makedirs(work_dir)
except OSError:
pass
return work_dir

Python, Permission denied only when dragging folder onto script

I have a script that is supposed to read a directory from its second argument and do various processes on it, and record the information to a second file, compressed.xml. Here's the code that causes errors:
targetpath = os.getcwd()
if len(sys.argv) >= 2:
targetpath = sys.argv[1]
with open("compressed.xml", "w") as f:
base = ntpath.basename(targetpath)
f.write("<" + base + ">\n")
f.write(getXML(targetpath, 1))
f.write("</" + base + ">\n")
When I run the script on the command line with a directory path as an argument, it works perfectly fine. But if I try to drag a folder onto the script from within File Explorer, it causes a "permission denied" error on compressed.xml. I can't really get more information about the traceback than that, because I don't really know how to get more info about it than using this simple catch;
except Exception as e:
raw_input(e)
Without it, the shell closes instantly upon causing an error, and I'm not able to see the traceback.

Categories

Resources