If I run "python /home/pi/temp/getTemp.py" from the terminal command line I get
"Error, serial port '' does not exist!" If I cd to the temp directory and run "python getTemp.py" it runs fine. Can anyone tell me why?
#!/usr/bin/env python
import os
import sys
import socket
import datetime
import subprocess
import signal
port = "/dev/ttyUSB0"
tlog = '-o%R,%.4C'
hlog = '-HID:%R,H:%h'
clog = '-OSensor %s C: %.2C'
def logStuff(data):
with open("/home/pi/temp/templog.txt", "a") as log_file:
log_file.write(data + '\n')
def main():
try:
output = subprocess.check_output(['/usr/bin/digitemp_DS9097U', '-q', '-a'])
for line in output.split('\n'):
if len(line) == 0:
logStuff("len line is 0")
continue
if 'Error' in line:
logStuff("error in output")
sys.exit()
line = line.replace('"','')
if line.count(',') == 1:
(romid, temp) = line.split(',')
poll = datetime.datetime.now().strftime("%I:%M:%S %p on %d-%B-%y")
content =(romid + "," + poll + "," + temp)
print content
return content
except subprocess.CalledProcessError, e:
print "digitemp error:\n", e.output
except Exception as e:
logStuff('main() error: %s' %e)
os.kill(os.getpid(), signal.SIGKILL)
if __name__ == "__main__":
main()
It probably cannot find the configuration file, which is normally stored in ~/.digitemprc when you run it with -i to initialize the network. If it was created in a different directory you need to always tell digitemp where to find it by passing -c
Related
In Python3 using subprocess.Popen, I would like to capture the output and command return code for this "nc -z 192.168.25.14 22" command. Here is my sample code:
#!/usr/bin/env python
import urllib.request, urllib.error, urllib.parse
import subprocess
import time
# set up null file for pipe messages
nul_f = open('/dev/null', 'w')
# try loop for clean breakout with cntl-C
try:
with open('/mnt/usbdrive/output/Urls.txt') as f:
for line in f:
data = line.split()
commands = ['nc', '-vZ', data[1], data[0]]
print(commands)
try:
ncdmp = subprocess.Popen(commands , stderr=subprocess.PIPE, stdout=subprocess.PIPE,)
except OSError:
print ("error: popen")
exit(-1) # if the subprocess call failed, there's not much point in continuing
ncdmp.wait()
if ncdmp.returncode != 0:
print(" os.wait:exit status != 0\n")
else:
print ("os.wait:", ncdmp.pid, ncdmp.returncode)
print("STDERR is ", ncdmp.stderr)
print("STDOUT is ", ncdmp.stdout)
print("STDIN is ", ncdmp.stdin)
except KeyboardInterrupt:
print('Done', i)
# clean up pipe stuff
ncdmp.terminate()
ncdmp.kill()
nul_f.close()
and an example of the output is
*Commands is ['nc', '-vZ', '192.168.25.14', '22']
os.wait:exit status != 0
STDERR is <_io.BufferedReader name=12>
STDOUT is <_io.BufferedReader name=9>
STDIN is <_io.BufferedWriter name=8>*
I'm assuming that I have an error in my code or logic, but I can not figure it out. I have used similar code for other commands like ssh and ls without issues. For this "nc" command I get the same set of output/messages regardless of whether or not there is an open port 22 at the host address.
Thanks...RDK
OK, as I did not get any useful replies to this question, I changed the code from subprocess.Popen to subprocess.run as shown below. This modification worked for my requirements as ncdup.stderr contained the information I was looking for.
commands = shlex.split("nc -vz " + "-w 5 " + data[1] + " " + data[0])
try:
ncdmp = subprocess.run(commands , capture_output=True)
except OSError:
print ("error: popen")
exit(-1)
err_line = str(ncdmp.stderr)
I am trying to develop a script which sends an email about checking ping regularly at one hour interval of time. I am using Python to program this script and I cannot create a log file to keep the ping logs which I need to mail. I'm new to using subprocess module and its functions.
import threading
import os
def check_ping():
threading.Timer(5.0, check_ping).start()
hostname = "www.google.com"
response = os.system("ping -c 4 " + hostname)
'''
def trace_route():
threading.Timer(5.0, trace_route).start()
hostname = "www.google.com"
response = os.system("traceroute" + hostname)
'''
check_ping()
#trace_route()
output = check_ping()
file = open("sample.txt","a")
file.write(output)
file.close()
import os, platform
import threading
def check_ping():
threading.Timer(10.0,check_ping).start()
hostname = "www.google.com"
response = os.system("ping " + ("-n 1 " if platform.system().lower()=="windows" else "-c 1 ") + hostname)
# and then check the response...
if response == 0:
pingstatus = "Network Active"
else:
pingstatus = "Network Error"
return pingstatus
pingstatus = check_ping()
This is what I came up with:
using subprocess instead of os.system
added timeout of 8 seconds
writing to csv file instead of txt file
added timestamps to csv file, without which I don't really see the point of logging in the first place
import os
import threading
import time
from subprocess import Popen, PIPE
def check_ping():
threading.Timer(10.0,check_ping).start()
# Get current time
timestamp = int(time.time())
# Build the command
hostname = "www.google.com"
if os.name == 'nt':
command = ['ping', '-n', '1', hostname]
else:
command = ['ping', '-c', '1', hostname]
# Create process
pingProcess = Popen(command, stdout=PIPE, stderr=PIPE)
try:
# Timeout 8 seconds, to avoid overlap with the next ping command
outs, errs = pingProcess.communicate(timeout=8)
except TimeoutExpired:
# If timed out, kill
pingProcess.kill()
outs, errs = pingProcess.communicate()
# Get the return code of the process
response = pingProcess.returncode
# and then check the response...
# These four lines can be removed, they are just to see if the system
# works.
if response == 0:
print("Network Active")
else:
print("Network Error")
# You most likely want a CSV file, as most programs accept this file type,
# including Microsoft Excel and LibreOffice Calc
# Further, I'm sure you want timestamps with the results.
file = open("ping.csv","a")
file.write(str(timestamp) + "," + str(response) + "\n")
file.close()
check_ping()
Here is another version without using the system's ping command, but instead using a python library for pinging. This ensures that the code works on all operating systems:
import threading
import time
from ping3 import ping
def check_ping():
threading.Timer(10.0,check_ping).start()
# Get current time
timestamp = int(time.time())
# Build the command
hostname = "www.google.com"
# Run ping
ping_result = ping(hostname, timeout=8)
ping_success = False if ping_result is None else True
# and then check the response...
# These four lines can be removed, they are just to see if the system
# works.
if ping_success:
print("Network Active (" + str(ping_result) + ")")
else:
print("Network Error")
# You most likely want a CSV file, as most programs accept this file type,
# including Microsoft Excel and LibreOffice Calc
# Further, I'm sure you want timestamps with the results.
file = open("ping.csv", "a")
ping_value_str = str(ping_result) if ping_success else "NaN"
file.write(str(timestamp) + "," + ("0" if ping_success else "1") + "," + ping_value_str + "\n")
file.close()
check_ping()
I'm trying to make python script (currently on windows) which will open some sub-processes (which will run infinitely) and script should periodically check do all of opened sub-processes still work correctly. So it should be done with while loop, I guess.
The sub-processes are about FFMPEG livestreaming.
The problem is when I do time.sleep(n) in my loop, because then every FFMPEG livestream stops, so I suppose time.sleep affect on all of child subprocesses.
I have no idea how to make it work.
Here is my python code:
import os, time, sys, datetime, smtplib, configparser, logging, subprocess, psutil
import subprocess
def forwardudpstream(channel_number, ip_input, ip_output):
try:
ffmpeg_command = 'ffmpeg -i udp://' + ip_input + ' -vcodec copy -acodec copy -f mpegts "udp://' + ip_output + '?pkt_size=1316"'
ffmpeg_output = subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False)
return str(ffmpeg_output.pid)
except:
print ("Exception!")
return '0'
while True:
configuration = 'config.ini'
channel_list_file = 'CHANNEL_LIST.conf'
pid_folder = "D:\\Forward_UDP_Stream\\pids\\"
channel_list = [line.rstrip('\n') for line in open(channel_list_file)]
for line in channel_list:
if not line.startswith('#') and ('|' in line):
channel_number, ip_input, ip_output = line.split('|')
print('----------')
print("Channel number = ", channel_number)
print("IP Input = ", ip_input)
print("IP Output = ", ip_output)
pid_file_found = False
print("Checking if pid file exists...")
for pidfile in os.listdir(pid_folder):
if pidfile.startswith(channel_number + '-'):
print("Pid file is found for this channel.")
pid_file_found = True
pid = int(pidfile.split('-')[1].split('.')[0])
print("PID = ", str(pid))
print("Checking if corresponding process is active...")
if not psutil.pid_exists(pid):
print("Process is not active.")
print("Removing old pid file.")
os.remove(pid_folder + pidfile)
print("Starting a new process...")
pid_filename = channel_number + '-' + forwardudpstream(channel_number, ip_input, ip_output) + '.pid'
pid_file = open(pid_folder + pid_filename, "a")
pid_file.write("Process is running.")
pid_file.close()
else:
print("Process is active!")
break
if pid_file_found == False:
print("Pid file is not found. Starting a new process and creating pid file...")
pid_filename = channel_number + '-' + forwardudpstream(channel_number, ip_input, ip_output) + '.pid'
pid_file = open(pid_folder + pid_filename, "a")
pid_file.write("Process is running.")
pid_file.close()
time.sleep(10)
Here is my CHANNEL_LIST.conf file example:
1|239.1.1.1:10000|239.1.1.2:10000
2|239.1.1.3:10000|239.1.1.4:10000
Perhaps there is some other solution to put waiting and sub-processes to work together. Does anyone have an idea?
UPDATE:
I finally make it work when I removed stdout=subprocess.PIPE part from the subprocess command.
Now it looks like this:
ffmpeg_output = subprocess.Popen(ffmpeg_command, stderr=subprocess.STDOUT, shell=False)
So now I'm confused why previous command was making a problem...?
Any explanation?
The following script is an extract from
https://github.com/RittmanMead/obi-metrics-agent/blob/master/obi-metrics-agent.py
The script is written in jython & it hits the weblogic admin console to extract metrics
The problem is it runs only once and does not loop infinitely
Here's the script that I've extracted from the original for my purpose:
import calendar, time
import sys
import getopt
print '---------------------------------------'
# Check the arguments to this script are as expected.
# argv[0] is script name.
argLen = len(sys.argv)
if argLen -1 < 2:
print "ERROR: got ", argLen -1, " args, must be at least two."
print '$FMW_HOME/oracle_common/common/bin/wlst.sh obi-metrics-agent.py <AdminUserName> <AdminPassword> [<AdminServer_t3_url>] [<Carbon|InfluxDB>] [<target host>] [<target port>] [targetDB influx db>'
exit()
outputFormat='CSV'
url='t3://localhost:7001'
targetHost='localhost'
targetDB='obi'
targetPort='8086'
try:
wls_user = sys.argv[1]
wls_pw = sys.argv[2]
url = sys.argv[3]
outputFormat=sys.argv[4]
targetHost=sys.argv[5]
targetPort=sys.argv[6]
targetDB=sys.argv[7]
except:
print ''
print wls_user, wls_pw,url, outputFormat,targetHost,targetPort,targetDB
now_epoch = calendar.timegm(time.gmtime())*1000
if outputFormat=='InfluxDB':
import httplib
influx_msgs=''
connect(wls_user,wls_pw,url)
results = displayMetricTables('Oracle_BI*','dms_cProcessInfo')
while True:
for table in results:
tableName = table.get('Table')
rows = table.get('Rows')
rowCollection = rows.values()
iter = rowCollection.iterator()
while iter.hasNext():
row = iter.next()
rowType = row.getCompositeType()
keys = rowType.keySet()
keyIter = keys.iterator()
inst_name= row.get('Name').replace(' ','-')
try:
server= row.get('Servername').replace(' ','-').replace('/','_')
except:
try:
server= row.get('ServerName').replace(' ','-').replace('/','_')
except:
server='unknown'
try:
host= row.get('Host').replace(' ','-')
except:
host=''
while keyIter.hasNext():
columnName = keyIter.next()
value = row.get(columnName )
if columnName.find('.value')>0:
metric_name=columnName.replace('.value','')
if value is not None:
if outputFormat=='InfluxDB':
influx_msg= ('%s,server=%s,host=%s,metric_group=%s,metric_instance=%s value=%s %s') % (metric_name,server,host,tableName,inst_name, value,now_epoch*1000000)
influx_msgs+='\n%s' % influx_msg
conn = httplib.HTTPConnection('%s:%s' % (targetHost,targetPort))
## TODO pretty sure should be urlencoding this ...
a=conn.request("POST", ("/write?db=%s" % targetDB), influx_msg)
r=conn.getresponse()
if r.status != 204:
print 'Failed to send to InfluxDB! Error %s Reason %s' % (r.status,r.reason)
print influx_msg
#sys.exit(2)
else:
print 'Skipping None value %s,server=%s,host=%s,metric_group=%s,metric_instance=%s value=%s %s' % (metric_name,server,host,tableName,inst_name, value,now_epoch*1000000)
I've tried to use the While loop, but that just stopped the code from exiting and not re-looping
What I want to achieve is to loop it infinitely post connection to weblogic
i.e. after this line
connect(wls_user,wls_pw,url)
and perhaps sleep for 5 seconds before re-running
Any and all help will be appreciated
Thanks
P
You can use this kind of condition for the loop :
mainLoop = 'true'
while mainLoop == 'true' :
and this for the pause between iterations :
java.lang.Thread.sleep(3 * 1000)
I have written wlst script to achieve the below tasks recursively
Stopping the applications
Undeploying the applications
Deploying the appliactions
When ever i execute the script, Either undeploy or Deploy happens only for 1 application. For other applications it fails with below error message.Can you please help me to fix the issue?
File "<iostream>", line 1116, in domainConfig
File "<iostream>", line 1848, in raiseWLSTException
WLSTException: Error cding to the MBean
<Feb 20, 2014 11:28:44 AM IST> <Warning> <JNDI> <BEA-050001> <WLContext.close() was called in a different thread than the one in which it was created.>
WLST Script what i have written
import sys
import os
import getopt
#========================
#Usage Section
#========================
def usage():
print "Usage:"
print "java weblogic.WLST manageApplication.py -u username -p password -a adminUrl [<hostname>:<port>] -t deploymentTarget\n"
print "java weblogic.WLST manageApplication.py -u weblogic -p weblogic1 -a t3://localhost:7001 -t AdminServer\n"
sys.exit(2)
#========================
#Connect To Domain
#========================
def connectToDomain():
try:
connect('weblogic','weblogic1','t3://localhost:7001')
print 'Successfully connected to the domain\n'
except:
print 'The domain is unreacheable. Please try again\n'
exit()
#========================
#Application undeployment Section
#========================
def undeployApplication():
cd ('AppDeployments')
myapps=cmo.getAppDeployments()
for appName in myapps:
domainConfig()
cd ('/AppDeployments/'+appName.getName()+'/Targets')
mytargets = ls(returnMap='true')
domainRuntime()
cd('AppRuntimeStateRuntime')
cd('AppRuntimeStateRuntime')
for targetinst in mytargets:
curstate4=cmo.getCurrentState(appName.getName(),targetinst)
print '-----------', curstate4, '-----------', appName.getName()
deploymentName=appName.getName()
deploymentTarget=targetinst
print deploymentName
print deploymentTarget
stopApplication(deploymentName, targets=deploymentTarget)
undeploy(deploymentName, targets=deploymentTarget)
#========================
#Input Values Validation Section
#========================
if __name__=='__main__' or __name__== 'main':
try:
opts, args = getopt.getopt(sys.argv[1:], "u:p:a:t:", ["username=", "password=", "adminUrl=", "deploymentTarget="])
except getopt.GetoptError, err:
print str(err)
username = ''
password = ''
adminUrl = ''
deploymentTarget = ''
for opt, arg in opts:
if opt == "-u":
username = arg
elif opt == "-p":
password = arg
elif opt == "-a":
adminUrl = arg
elif opt == "-t":
deploymentTarget = arg
if username == "":
print "Missing \"-u username\" parameter.\n"
usage()
elif password == "":
print "Missing \"-p password\" parameter.\n"
usage()
elif adminUrl == "":
print "Missing \"-a adminUrl\" parameter.\n"
usage()
elif deploymentTarget == "":
print "Missing \"-c deploymentTarget\" parameter.\n"
usage()
#========================
#Main Control Block For Operations
#========================
def deployMain():
for line in open("c:\\wlst\\applicationsList.txt"):
temp_line = line
fields = temp_line.strip().split(",")
print(fields[0]+" "+fields[1])
deploymentName = fields[0]
deploymentFile = fields[1]
print deploymentName+" "+deploymentFile+" "+deploymentTarget+"/n"
deploy(deploymentName,deploymentFile,targets=deploymentTarget)
#==================
#main block
#=====================
connectToDomain()
undeployApplication()
deployMain()
disconnect()
WLContext.close() is probably not the real problem (it's even in some of the Oracle examples). What error messages do you see when deploy and undeploy are being called?
You should see something like:
Deploying application from /tmp/something/myapp.ear
Current Status of your Deployment:
Deployment command type: deploy
Deployment State : completed
Deployment Message : no message
I also see that you never call activate() at the very end of your script so that could be the issue if you are running in production mode.
Try adding the following at the very end of your script after deployMain():
save()
status = activate(300000, "block='true'")
status.getStatusByServer()
status.getDetails()
UPDATE:
The activation error occurs because you have not called edit() before the undeploy:
# Get edit/lock for upcoming changes
edit()
startEdit(120000, 120000, 'false')
undeployApplication()
I think you will be better off greatly simplifying your undeploy. You don't need to go through the complexity of determining targets because you are already undeploying from ALL targets. Try this instead and see if you can make progress:
cd ('AppDeployments')
myapps=cmo.getAppDeployments()
for appName in myapps:
try:
appPath = "/AppDeployments/" + appName.getName()
cd(appPath)
print "Stopping deployment " + appName.getName()
stopApplication(appName.getName())
print "Undeploying " + appName.getName()
undeploy(appName.getName(), timeout=60000)
except Exception , e:
print "Deployment " + appName.getName() + " removal failed."