I am having trouble trying to get this script to work. When I debug this code it will not read into the class or functions. The code will not execute properly. Has anyone know the problem here, Thanks
#!/home/build/test/Python-2.6.4
import os, subprocess
class mks_function:
sandbox="new_sandbox"
def mks_create_sandbox():
try:
retcode=call("si createsandbox" + "--no --hostname=bel --port=70 --user=user --password=1234 --populate --project=e:/project.pj --lineTerminator=lf new_sandbox", shell=True)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError, e:
print >>sys.stderr, "Execution failed:", e
print "sandbox retVal="+retcode
print "Creating a new sandbox called "+sandbox+" "
###############################################################
Few things to check your code
call should be subprocess.call
better use full path when you call for example, /usr/bin/si createsandbox, you can check with which si in shell
instead of concatenating the commands "si createsandbox" + "--no ...", please use list ["/usr/bin/si","createsandbox --no ..."]
you didn't import sys, but using it
sandbox should be self.sandbox and def mks_create_sandbox(): should be def mks_create_sandbox(self):
Use an IDE for example Ulipad.
Try put as the first line:
#!/usr/bin/env python
If you really need specific version of Python, setup your environment before running.
Possible problems:
your code is never executed (it's like you define the class only). Use it in the file (names are misleading):
if __name__ == '__main__':
myObject = mks_function()
show us how are you executing the code? Have you changed the permissions to be able to run the script?
chmod +x filename.py
or are you trying to start it as:
python filename.py
Related
I have a really complicated Python script going on, sometimes it just gets an error, and the only way to debug this, is restarting it, because everything else would make no sense and the error would come back in no time (I already tried a lot of things, so please dont concentrate on that)
I want a .bat script (im on Windows unfortunately) that restarts my python script, whenever it ends.
Another python script is also fine.
How can I do that?
Thanks in advance
set env=python.exe
tasklist /FI "IMAGENAME eq python.exe" 2>NUL | find /I /N "python.exe">NUL if "%ERRORLEVEL%"!="0(
start python script.py
)
Other way from python to execute python
import subprocess
from subprocess import call
def processExists(processname):
tlcall = 'TASKLIST', '/FI', 'imagename eq %s' % processname
# shell=True hides the shell window, stdout to PIPE enables
# communicate() to get the tasklist command result
tlproc = subprocess.Popen(tlcall, shell=True, stdout=subprocess.PIPE)
# trimming it to the actual lines with information
tlout = tlproc.communicate()[0].strip().split('\r\n')
# if TASKLIST returns single line without processname: it's not running
if len(tlout) > 1 and processname in tlout[-1]:
print('process "%s" is running!' % processname)
return True
else:
print(tlout[0])
print('process "%s" is NOT running!' % processname)
return False
if not processExists('python.exe')
call(["python", "your_file.py"])
I have a script (Python) that check if I have the right modules installed and if they are up to date -- at least a certain version. I want to run this script in the scons Configure phase. I tried something like:
print 'Configuring... '
conf = Configure(env)
print 'Checking Python modules ',
ret = conf.TryRun("""#!/usr/bin/env python
print 'ook' # test
import my_script
my_script.run()
""", '.py')
if ret == (0, ''):
print 'Fail'
sys.exit(2)
env = conf.Finish()
But all I get is (0, '') which means that TryRun failed but I cannot see why it would fail! Any idea as to what I am doing wrong?
This does the trick but is not very elegant:
from subprocess import call
if call(os.path.join(os.getcwd(), 'my_script.py')):
sys.exit(2)
I am still looking for a more elegant solution.
I am using python-daemon in my code that has print statements in it. I want to send them to a file so I ran the following:
python server.py >> log.out
However, nothing goes in log.out.
Can anyone tell me what I need to do?
Thanks.
The DaemonContext object allows redirecting stdout/stderr/stdin when you create the object. For example:
import os
import daemon
if __name__ == '__main__':
here = os.path.dirname(os.path.abspath(__file__))
out = open('checking_print.log', 'w+')
with daemon.DaemonContext(working_directory=here, stdout=out):
for i in range(1, 1000):
print('Counting ... %s' % i)
You should be able to cat checking_print.log and see the output from the print statements.
A good reference for the DaemonContext object is PEP 3143.
if you have an error in your code it will not be written to the file. See http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-3.html
Try creating this file:
print 'stdout'
raise Exception('stderr')
If it's already running as a daemon you'll most likely need to force redirection of STDOUT, STDERR etc. You can read more on I/O Redirection here.
python server.py 2>log.out >&2
Folks
I am not very up with Python but have inherited a load of Python scripts
One of which is given me a issue in that I am not 100% sure what one line is running
What I need to do is print out the command line and its variables.
The line in question is
ldapModify(userdn, mods, uri=uri)
What I am hoping to see is something like
/usr/bin/ldapmodify xxxx cn=......
Can any kind soul help.
The Python ldap lib doesn't call on the ldap command line client, it binds directly to the underlying system ldap lib.
If what you want is to know the values of the args passed to ldapModify, it's quite simple: print them to sys.stderr :
import sys
try:
ldapModify(userdn,mods,uri=uri)
except Exception, e:
print >> sys.stderr, "oops, ldapModify failed with '%s'" % e
print >> sys.stderr, "userdns : '%s' - uri : '%s' - mods : '%s'" % (userdns, uri, mods)
# and reraise the error so you get the whole traceback
raise
Before the line in question, you could place a call to python's interactive debugger. Then you can print out the variables in question:
import pdb
pdb.set_trace()
ldapModify(userdn, mods, uri=uri)
At the (pdb) prompt you can print out the value of any or all of the variables.
Here's a link about the debugger.
I am trying to run a Python program to see if the screen program is running. If it is, then the program should not run the rest of the code. This is what I have and it's not working:
#!/usr/bin/python
import os
var1 = os.system ('screen -r > /root/screenlog/screen.log')
fd = open("/root/screenlog/screen.log")
content = fd.readline()
while content:
if content == "There is no screen to be resumed.":
os.system ('/etc/init.d/tunnel.sh')
print "The tunnel is now active."
else:
print "The tunnel is running."
fd.close()
I know there are probably several things here that don't need to be and quite a few that I'm missing. I will be running this program in cron.
from subprocess import Popen, PIPE
def screen_is_running():
out = Popen("screen -list",shell=True,stdout=PIPE).communicate()[0]
return not out.startswith("This room is empty")
Maybe the error message that you redirect on the first os.system call is written on the standard error instead of the standard output. You should try replacing this line with:
var1 = os.system ('screen -r 2> /root/screenlog/screen.log')
Note the 2> to redirect standard error to your file.