how to capture the output value of a running python script - python-3.x

I have a python script the name is "nimbang.py" which is currently running and showing output continuously.
and this is the code from "nimbang.py"
import serial
ser = serial.Serial("COM1", 9600, timeout = 1)
while True :
if ser.isOpen():
input_data = ser.readline()
value = str(input_data)
print(value)
from that script i will get value run continuously
now i try to catch the output from nimbang.py every 1 minutes using another python script name readnimbang.py
in this readnimbang.py i try this code to make sure that this script can communicate with the output from nimbang.py :
def read_nimbang():
a = input("Read yes or no ?")
if a == "yes"
import nimbang
from nimbang import value
print(value)
read_nimbang()
when i run, i get errorr :
serial.Serialutil.SerialException: couldnot open port 'COM1':permissionError(13. 'Access is denied.',None, 5)

Related

unable to write command on serial port on a single attempt

I am currently trying to read the output of writing a command to the serial port where my USB device is connected.
import pyserial
ser = serial.Serial(port=portName,baudrate=19200,parity=serial.PARITY_NONE,stopbits=serial.STOPBITS_ONE,bytesize=serial.EIGHTBITS)
ser.xonxoff = 0
ser.rtscts = 0
ser.set_buffer_size(rx_size=256, tx_size=256)
ser.writeTimeout = 2
ser.timeout = 2
ser.write("\r".encode())
if not ser.is_open:
ser.open()
try:
ser.flushInput()
ser.flushOutput()
ser.write(command.encode())
return ser.readlines()
finally:
ser.close()
I always have to run this code twice in order to execute a command. What parameter should I change here in order to not have this issue?

Is it possible to interact with the subprocess 3 standards streams on windows?

I have a script that opens a subprocess, this process awaits multiple inputs.
I tried with subprocess.Popen() but when combining the 3 standards streams it gets stuck in deadlocks...
So I tired to use wexpect (Apparently Windows version of pexecpt) it also didn't worked.
Now I'm using Sarge and my code right now looks like this:
import os
import subprocess
import sarge
import sys
def get_env():
env = os.environ.copy()
return env
def interactive(list_command: list, instruction_dict: dict):
env = get_env()
std_out = ""
for a_number in instruction_dict:
capture_stdout = sarge.Capture(buffer_size=-1)
capture_stderr = sarge.Capture(buffer_size=-1)
child_proc = sarge.Command(list_command, stdout=capture_stdout, stderr=capture_stderr,
shell=True, env=env)
child_proc.run(input=subprocess.PIPE,
async_=True)
print(capture_stdout.readlines(timeout=1.0), capture_stderr.readlines(timeout=1.0))
if instruction_dict[a_number][0] is not None:
#if capture_stdout.expect(instruction_dict[a_number][0]) is not None or capture_stderr.expect(instruction_dict[a_number][0]) is not None:
# self.test_manager.log_event(msg="found line : " + instruction_dict[a_number][0] + "in PIPE", current_event_type=LogLevel.DEBUG, screen_only=False)
print("in exec line : ", child_proc.stdout.readline(timeout=1.0), child_proc.stderr.readlines(timeout=1.0))
else:
print("in exec line : ", child_proc.stdout.readlines(timeout=1.0), child_proc.stderr.readlines(timeout=1.0))
if instruction_dict[a_number][1] is not None:
print(f"sending \"{instruction_dict[a_number][1]}\" to process in interactive")
temp_bytes = str.encode((instruction_dict[a_number][1]+"\n"))
child_proc.stdin.write(temp_bytes)
try:
child_proc.stdin.flush() # blind flush
except:
pass
print("Last line : ", child_proc.stdout.readlines(timeout=1.0), child_proc.stderr.readlines(timeout=1.0))
child_proc.wait()
std_out += child_proc.stdout.read().decode('utf-8')
child_proc.kill() # kill the subprocess
print("output: ", std_out)
interactive(list_command=["process.exe", "-delete_datamodel", "MODELNAME"],instruction_dict={1 : (None, "y")})
Output looks like this:
[] []
in exec line : [] []
send "y" to process in interactive
Last line : [] [b'User root connected to DB MODELNAME\r\n']
output: Are you sure to delete DB MODELNAME? (y/n)\n\nDelete Data Model Ok\n
In console it looks like this:
C:\>process.exe -delete_data_model -db_name MODELNAME
Are you sure to delete DB MODELNAME ? (y/n)
y
User root connected to DB MODELNAME
Delete Data Model Ok
There are multiple problems:
I can't catch the first stdout "Are you sure to delete DB MODELNAME ? (y/n)" during the loop I only get [].
capture_stdout.expect crash but in fact it might be the same problem as the first one, if it can't read the first stdout.
lines are going in stderr instead of stdout (it might be because of the process, I don't know how to test this)
for another command I ll need to answer more than one interactive by looking of the question before answering them that way my instruction_dict will look like this
instruction_dict = {1 : ("Are you sure to recover the DB", "y"),
2 : ("Do you want to stop the service", "y"),
3 : ("Do you want to stop the DB", "y"),
4 : ("Do you want to drop and create the DB", "y")}
Is this even possible? I have search for a working exemple and didn't found one, I know I might be bad at searching but...
Sorry for the terrible syntax(and bad english), I want to know if there is a pure python solution (I have one solution working in tcl but I'm trying to get rid of it/ I didn't wrote the tcl code).

Python code for telnetting DUT needs further optimization

I need to further optimize my code in Python.
I was earlier executing commands on the Device Under Test step by step which was a lot as I also required sleep timers. However I was able to minimize it through a list and calling elements of the list in a for loop:
I need your inputs to further optimize this code:
ConfigListBFD = ['conf t' , 'int Fa1/0' , 'ip address 10.10.10.1 255.255.255.0', 'no shut']
for i in ConfigListBFD:
tn.write(i.encode('ascii') + b"\n")
print (i, "command entered successfully")
time.sleep(2)
Please note: I am telnetting the DUT as ssh is not supported.
i am using this optimized common code for telnet. we can create a common file where you can add this method
import telnetlib
import time
def telnet(host):
user = <username>
password = <password>
try :
tn = telnetlib.Telnet(host)
except :
print("Unable to connect")
sys.exit()
tn.read_until(b"Username:") # read until username prompt
tn.write(user.encode('ascii') + b"\n")
if password:
tn.read_until(b"password:") #read until password prompt
tn.write(password.encode('ascii') + b"\n")
tn.read_until(b"#")
return tn #return telnetlib handle
than import this method to another file, where we write our script

Can't receive the data from device RFB2000 in python

I am using the module "ctypes" to load RFBClient.dll,I use windll and the convention is stdcall. I want to remote control the device RFB2000 with these commands below:
first step for connection
All the commands
for my programme, the connection is successful but the problem is that i can't recieve the data, when I want to get temperature value, I call the function but it always returns 0, the restype is c_double and the argtypes is none, I can't see there is any problem. English is not my native language; please excuse typing errors.
import ctypes
import time
libc = ctypes.WinDLL("X:\\RFBClient.dll")
#connect to RFB software
libc.OpenRFBConnection(ctypes.c_char_p('127.0.0.1'.encode('UTF-8')))
#check if connection successful
libc.Connected()
#Set parameters
#num_automeas = 1; %Number of auto-measurement runs.
completion_count = 2; #% Number of On-Off pairs within each auto-measurement run.
OnHalfCycleTimeCount = 40; # set 2s on
OffHalfCycleTimeCount = 40; # set 2s off
Data=[]
libc.SetCompletionCount(completion_count)
libc.SetMeasureUntilCount(completion_count)
libc.SetOnHalfCycleCount(OnHalfCycleTimeCount)
libc.SetOffHalfCycleCount(OffHalfCycleTimeCount)
libc.NewAutoMeasurement()
#zeroing
time.sleep(1)
print("zeroing.....")
libc.Zero()
while libc.Zeroing()== -1:
time.sleep(1)
#libc.CheckingSensor()
print("measurement start")
libc.StartMeas()
time.sleep(0.5)
while libc.Measuring() == -1:
time.sleep(1)
print(libc.Measuring())
getTemperature = libc.GetTemperature
getTemperature.restype = ctypes.c_double
getTemperature.argtypes = []
print(getTemperature())

Execute python scripts from another python script opening another shell

I'm using python 3, I need one script to call the other and run it in a different shell, without passing arguments, I'm using mac os x, but I need it to be cross platform.
I tried with
os.system('script2.py')
subprocess.Popen('script2.py', shell=true)
os.execl(sys.executable, "python3", 'script2.py')
But none of them accomplish what I need.
I use the second script to get inputs, while the first one handles the outputs...
EDIT
This is the code on my second script:
import sys
import os
import datetime
os.remove('Logs/consoleLog.txt')
try:
os.remove('Temp/commands.txt')
except:
...
stopSim = False
command = ''
okFile = open('ok.txt', 'w')
okFile.write('True')
consoleLog = open('Logs/consoleLog.txt', 'w')
okFile.close()
while not stopSim:
try:
sysTime = datetime.datetime.now()
stringT = str(sysTime)
split1 = stringT.split(" ")
split2 = split1[0].split("-")
split3 = split1[1].split(":")
for i in range(3):
split2.append(split3[i])
timeString = "{0}-{1}-{2} {3}:{4}".format(split2[2], split2[1], split2[0], split2[3], split2[4])
except:
timestring = "Time"
commandFile = open('Temp/commands.txt', 'w')
command = input(timeString + ": ")
command = command.lower()
consoleLog.write(timeString + ': ' + command + "\n")
commandFile.write(command)
commandFile.close()
if command == 'stop simulation' or command == 'stop sim':
stopSim = True
consoleLog.close()
os.remove('Temp/commands.txt')
and this is where I call and what for the other script to be operative in script 1:
#Open console
while not consoleOpent:
try:
okFile = open('ok.txt', 'r')
c = okFile.read()
if c == 'True':
consoleOpent = True
except:
...
Sorry for the long question...
Any suggestion to improve the code is welcomed.
Probably the easiest solution is to make the contents of you second script a function in the first script, and execute it as a multiprocessing Process. Note that you can use e.q. multiprocessing.Pipe or multiprocessing.Queue to exchange data between the different processes. You can also share values and arrays via multiprocessing.sharedctypes.
This will be platform-dependent. Here a solution for Mac OS X.
Create new file run_script2 with this content:
/full/path/to/python /full/path/to/script2.py
Make it executable.: chmod +x run_script2
Run from Python with:
os.system('open -a Terminal run_script2')
Alternatively you can use: subprocess.call.
subprocess.call(['open -a Terminal run_script2'], shell=True)
On Windows you can do something similar with (untested):
os.system('start cmd /D /C "python script2.py && pause"')

Resources