I have a python script which takes a Java jar file from my Continuous Integration Server and starts it after each build. I am getting a strange error when I attempt to run the Jar file though, "[Error 2] The system cannot find the file specified". Now this would make sense if the file I am looking to utilize was missing or I had the wrong path, but os.path.exists() returns true on the file just before the WindowsError occurs. So, I am wondering which file can't be found... perhaps some part of my startup command is being interpreted as a file argument (which would understandably be missing)? So my question is, how do I discover which file Windows is failing to find in the case of error 2?
To ensure that my issue is not related to some other error in my script, here are the relevant bits:
serverConstants.py:
import os
__author__ = 'Brendon Dugan'
serverJarName = "eloquence-server.jar"
backupJarName = "eloquence-server-backup.jar"
deployedJarName = "eloquence-server-jar-with-dependencies.jar"
serverLocation = os.path.join("C:" + os.path.sep, "eloquence-alpha")
serverFlag = "-isServer=true"
javaVariant = "javaw"
javaExecutable = os.path.join(os.environ["JAVA_HOME"], "bin", javaVariant)
serverStartCommand = ("start \"Eloquence Server\" /d" +
serverLocation + " \"" + javaExecutable + "\" -jar " +
os.path.join(serverLocation, serverJarName) + " " + serverFlag)
startServer.py:
import os
import subprocess
import traceback
import psutil
import serverConstants
def startServer(server):
if os.path.exists(server):
print "Server seems to exist"
os.chdir(serverConstants.serverLocation)
kwargs = {}
DETACHED_PROCESS = 0x00000008
CREATE_NEW_PROCESS_GROUP = 0x00000200
kwargs.update(creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)
try:
print serverConstants.serverStartCommand
print os.getcwd()
eloquenceProcess = subprocess.Popen(serverConstants.serverStartCommand, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kwargs)
print eloquenceProcess.pid
print "Server started successfully"
return 0
except WindowsError, error:
print "A Windows Error Has Occurred"
print error.strerror
print error
print "An error occurred while starting the server"
return 1
if __name__ == "__main__":
print "Preparing to start server"
server = os.path.join(serverConstants.serverLocation, serverConstants.serverJarName)
print server
if startServer(server) == 0:
exit(0)
exit(1)
Full Program Output:
Preparing to start server
C:\eloquence-alpha\eloquence-server.jar
Server seems to exist
start "Eloquence Server" /dC:\eloquence-alpha "C:\Program Files\Java\jdk1.7.0_11\bin\javaw" -jar C:\eloquence-alpha\eloquence-server.jar -isServer=true
C:\eloquence-alpha
A Windows Error Has Occurred
The system cannot find the file specified
[Error 2] The system cannot find the file specified
An error occurred while starting the server
Process finished with exit code 1
Related
I wanted to use PowerShell command through Python so I got this function
Functions.py:
import subprocess as sp
def makeconnection():
proc = sp.Popen('powershell add-vpnconnection ...my credentials...', stdout= sp.PIPE)
if __name__ == "__main__":
makeconnection()
Main.py:
from Functions import makeconnection
#...Codes...
try:
appdatapath = os.getenv('appdata')
with open(appdatapath + r'\Microsoft\Network\Connections\Pbk\rasphone.pbk', "r+") as f:
if f.read().find('CookieVPN') != -1:
print("VPN Connection: OK")
else:
#1. This code doesn't work
makeconnection()
#2. Then if I replace the line above with this one it works
proc = sp.Popen('powershell add-vpnconnection ...my credentials...', stdout=sp.PIPE)
print("VPN Connection: Created")
except Exception as e:
print('\n\nSomething went wrong while accessing the connection\n' + '-' * 15)
print(e)
input('\n\n *** Press Enter To Exit ***')
sys.exit()
#...Rest of the Codes...
It
works fine on its own but if I import this into another .py file and call it from there it raises the "permission denied" error from PowerShell.
What causes this and how to fix it?
I'm trying to debug a python script using logger.
It opens another python script and checks whether it's running or not.
If not then it restarts that script.
My script:
while True:
print("Restart")
logger.info("Restart")
try:
p = subprocess.Popen(["python", OPEN_FILE]).wait()
except:
logger.exception("Error opening script")
print("Exit")
logger.error("Exit")
time.sleep(10)
if p != 0:
continue
else:
break
If file is not found then it prints error on terminal:
pi#raspberrypi:~/Desktop/MODBUS_TCP $ sudo python py_restart_script.py
Restart
python: can't open
file'/home/pi/Desktop/MODBUS_TCP/API_Modbus_TCP_Server3.py': [Errno 2] No
such file or directory
Exit
But that error is not in the log file:
2018-11-15 22:30:16,269 - INFO - Restart
2018-11-15 22:30:16,325 - ERROR - Exit
How to log same error showing in terminal to the log file?
What's printed in the terminal is process stderr output. You can get it in your python script and print it in the log file
>>> import subprocess
>>> p = subprocess.Popen(["python", "foobar"], stderr=subprocess.PIPE)
>>> ret = p.wait()
>>> ret # this holds the `subprocess` return code. ret != 0 indicates an error
2
>>> (_, stderr) = p.communicate()
>>> stderr
"python: can't open file 'foobar': [Errno 2] No such file or directory\n"
>>>
Does anyone know if you can catch os errors in python. I am working on a script that is mapping network drives.
If the end user types the name of a path that does not exist no error shows up and that could become an issues.
I am using the subprocess module, with python version 3.6, along with the pycharm IDE.
If I map to a location that does not exist I get the following error "System error 53 has occurred. The network path was not found."
Lastly I have tried catching the error using OSError, Exception, and BaseException. Each one that I have used does not return any error message.
Here is an example of the script that I am running.
def StoreInfo():
receiving = input("Enter receiving: ")
try:
subprocess.call(r'net use y: \\' + receiving + '\\act\\rto\\transent', shell=True) #timeout=30
except OSError:
#print("An unexpected error:" , sys.exc_info()[0])
print(sending+"'s path does not exit!")
StoreInfo()
Python ยป Documentation Subprocess
try:
retcode = call("mycmd" + " myarg", shell=True)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError as e:
print >>sys.stderr, "Execution failed:", e
test1.py:
process = Popen(["python","test2.py"])
time.sleep(3)
alive = process.poll()
if alive is None:
print "Still running"
else:
print "Not running\r\n"
print "%r" % alive
test1.py Output:
Not running
2
test2.py:
time.sleep(30)
print "done"
What is going on? Shouldn't this return "Still running"?
Because of a contradicting result here's the full test1.py code:
import cStringIO
import os
import cgi
import time
from subprocess import Popen
def application(environ, start_response):
headers = []
headers.append(('Content-Type', 'text/plain'))
write = start_response('200 OK', headers)
input = environ['wsgi.input']
output = cStringIO.StringIO()
process = Popen(["python","test2.py"])
time.sleep(3)
alive = process.poll()
if alive is None:
print >> output, "Still running"
else:
print >> output, "Not running\r\n"
print >> output, "%r" % alive
output.write(input.read(int(environ.get('CONTENT_LENGTH', '0'))))
return [output.getvalue()]
Updated test1.py:
process = Popen(["python","C:/wamp/www/python/popen/test2.py"], shell=True)
time.sleep(5)
alive = process.poll()
if alive is None:
#print >> output, "%r" % alive
print >> output, "Still running"
else:
print >> output, "Not running"
print >> output, "%r" % alive
print >> output, "Current working dir : %s" % os.getcwd()
print >> output, os.strerror(0)
Updated Output:
Not running
0
Current working dir : C:\wamp\bin\apache\apache2.2.22
No error
If Popen() cannot find test2.py, it produces the error "No such file or directory", with errno 2. This error number is returned by poll(). Since you seem to be running this script through wsgi, something seems to be gulping your stderr and you don't see the error message:
$ cat test1.py
from subprocess import Popen
import time
process = Popen(["python","doesnotexist.py"])
time.sleep(3)
alive = process.poll()
if alive is None:
print "Still running"
else:
print "Not running\r\n"
print "%r" % alive
$ python test1.py
python: can't open file 'doesnotexist.py': [Errno 2] No such file or directory
Not running
2
Now, the issue is probably because your current working directory of your script is not set to the script's directory by the front end server, try printing os.getcwd() to see if it's what you're expecting.
According to this
An exit status of 2 indicates an issue with the shell executing the command. Have you tried running test2.py directly in the shell to verify there aren't issues with it? As Lie pointed out it could be that the shell can't find the file you're trying to execute, though there could be another issue causing it to break.
I have been working on a project that takes a MySQL dump and restores a database with the information that a user provides. I keep getting a file can not be found error then my custom error for debugging stating that. OS command has failed.
try:
username = self.username.get()
password = self.password.get()
database = self.database.get()
file = self.filename
print str(username)
print str(file)
test = os.system("mysql -u" + username + " -p" + password + " " + database + " <" + file)
if (test != 0):
print "OS COMMAND FAILED"
else:
print "pass"
print test
except:
print "fail"
print "Unexpected error:", sys.exc_info()[0]
raise
I will also continue to do research just in case I find the solution. I have been looking at the os.system command but the problem goes away if I specify the file name right in the command instead of retrieving it from a variable.
All the variables are pulled from entry boxes. There is no way for a user to type the file name incorectly as the program populates the filename based on a openfiledialog box and does not allow for the user to edit that box.
Error text:
C:/Documents and Settings/XPMUser/Desktop/src/database.sql
root
The system cannot find the file specified.
OS COMMAND FAILED
1
If there is a space in the filename, that will cause the kind of problem you describe. The shell will parse the space as being a delimiter. You may want to do something like
import pipes
...
database + " < " + pipes.quote(filename)
Better yet, use the subprocess module
test = subprocess.call(['mysql', '-u', username, '-p', password, database],
stdin=open(file))