python output from subprocess.Popen - python

I'm trying to write a simple software to scan some bluetooth devices (beacon with advertising) and I have a problem with the instruction subprocess.Popen
p1 = subprocess.Popen(['timeout','10s','hcitool','lescan'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
p1.wait()
output, error = p1.communicate()
print("stdout: {}".format(output))
print("stderr: {}".format(error))
the output and error variables are empty!
If I remove the stdout=subprocess.PIPE,stderr=subprocess.PIPE from the Popen I can see the right result in the console, if I change the command with ['ls','-l'] it works fine and I see the result in the variables .
I've tryed with subprocess.run (with the timeout) and it is the same.
If I don't use the timeout obviously the command never ends.
I can't use pybluez and my python version is the 3.7
Can someone help me?

Solved using ['timeout','-s','INT','10s','hcitool','lescan'] as command instead of ['timeout','10s','hcitool','lescan'].
Maybe in the second case the process was not killed well and I didn't receive the output.
Thank you the same.

Related

Python2 Popen in Windows

I was trying to execute a windows console exe program using Popen on python 2.
import subprocess
#
# Other codes
#
p = subprocess.Popen(path_of_exe, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output = p.stdout.read()
print output
p.stdin.write('mystring')
The program prints Command> when the program executed.
However, the output variable has nothing about the string.
It is always an empty string.
If I change stdout=subprocess.PIPE to stdout=sys.stdout, it printed outputs.
However, I need to get the output to parse the result from my input.
So, I want to grep the output was program.
I'm not sure why the subprocess.PIPE doesn't work.
Also, when I changed to stdout=sys.stdout, its output printed Command> infinitely.
The program should print the Command> only one time before I put string.
I also tried to get the output using p.communicate()[0], but it doesn't work.
I'm no idea with this behavior. When I worked in a Linux environment, there is no problem like that. I might think it is a problem of stdin or stdout buffer even though flush not worked.
I have tackled this problem before. Try and use this syntax when using Popn on Python2.
p=subprocess.Popen([python(where your python is located), file name, args],stdout=PIPE).stdout.read()
Let me know if this worked out for ya!

My python subprocess call did not work in crontab why?

My current approach is to first remove the old model, save the new model , using the shell is no problem , but it just doesn't work automatically using crontab. Any idea why or how to solve this? Thanks for the help.
The error is that main programm does not wait for the subprocess.call to return. I think that this is the problem but not sure.
This is my current command:
subprocess.call('dse hadoop fs -rmr /root/recommend_model', shell=True)
A possible solution just to check that it was correctly executed is to wait a returncode.
Here the link to subprocess module:
https://docs.python.org/2/library/subprocess.html
You can wait the return code in you script:
if (subprocess.call(command, args) == 0):
print("We are proceeding)
else:
print("Something went wrong executing %s" % command)
Additionally try as suggested to redirect to a log file your script execution with 2>&1 > mickey.log
Last but not least some subprocess/os.system suggestions available here:
Controlling a python script from another script
python: run external program and direct output to file and wait for finish
Please let me know if this solve your issue.

Wait for subprocess .exe to finish before proceeding in Python

I'm running an application from within my code, and it rewrites files which I need to read later on in the code. There is no output the goes directly into my program. I can't get my code to wait until the subprocess has finished, it just goes ahead and reads the unchanged files.
I've tried subprocess.Popen.wait(), subprocess.call(), and subprocess.check_call(), but none of them work for my problem. Does anyone have any idea how to make this work? Thanks.
Edit: Here is the relevant part of my code:
os.chdir('C:\Users\Jeremy\Documents\FORCAST\dusty')
t = subprocess.Popen('start dusty.exe', shell=True)
t.wait()
os.chdir('C:\Users\Jeremy\Documents\FORCAST')
Do you use the return object of subprocess.Popen()?
p = subprocess.Popen(command)
p.wait()
should work.
Are you sure that the command does not end instantly?
If you execute a program with
t = subprocess.Popen(prog, Shell=True)
Python won't thrown an error, regardless whether the program exists or not. If you try to start an non-existing program with Popen and Shell=False, you will get an error. My guess would be that your program either doesn't exist in the folder or doesn't execute. Try to execute in the Python IDLE environment with Shell=False and see if you get a new window.

IOError Input/Output Error When Printing

I have inherited some code which is periodically (randomly) failing due to an Input/Output error being raised during a call to print. I am trying to determine the cause of the exception being raised (or at least, better understand it) and how to handle it correctly.
When executing the following line of Python (in a 2.6.6 interpreter, running on CentOS 5.5):
print >> sys.stderr, 'Unable to do something: %s' % command
The exception is raised (traceback omitted):
IOError: [Errno 5] Input/output error
For context, this is generally what the larger function is trying to do at the time:
from subprocess import Popen, PIPE
import sys
def run_commands(commands):
for command in commands:
try:
out, err = Popen(command, shell=True, stdout=PIPE, stderr=PIPE).communicate()
print >> sys.stdout, out
if err:
raise Exception('ERROR -- an error occurred when executing this command: %s --- err: %s' % (command, err))
except:
print >> sys.stderr, 'Unable to do something: %s' % command
run_commands(["ls", "echo foo"])
The >> syntax is not particularly familiar to me, it's not something I use often, and I understand that it is perhaps the least preferred way of writing to stderr. However I don't believe the alternatives would fix the underlying problem.
From the documentation I have read, IOError 5 is often misused, and somewhat loosely defined, with different operating systems using it to cover different problems. The best I can see in my case is that the python process is no longer attached to the terminal/pty.
As best I can tell nothing is disconnecting the process from the stdout/stderr streams - the terminal is still open for example, and everything 'appears' to be fine. Could it be caused by the child process terminating in an unclean fashion? What else might be a cause of this problem - or what other steps could I introduce to debug it further?
In terms of handling the exception, I can obviously catch it, but I'm assuming this means I wont be able to print to stdout/stderr for the remainder of execution? Can I reattach to these streams somehow - perhaps by resetting sys.stdout to sys.__stdout__ etc? In this case not being able to write to stdout/stderr is not considered fatal but if it is an indication of something starting to go wrong I'd rather bail early.
I guess ultimately I'm at a bit of a loss as to where to start debugging this one...
I think it has to do with the terminal the process is attached to. I got this error when I run a python process in the background and closed the terminal in which I started it:
$ myprogram.py
Ctrl-Z
$ bg
$ exit
The problem was that I started a not daemonized process in a remote server and logged out (closing the terminal session). A solution was to start a screen/tmux session on the remote server and start the process within this session. Then detaching the session+log out keeps the terminal associated with the process. This works at least in the *nix world.
I had a very similar problem. I had a program that was launching several other programs using the subprocess module. Those subprocesses would then print output to the terminal. What I found was that when I closed the main program, it did not terminate the subprocesses automatically (as I had assumed), rather they kept running. So if I terminated both the main program and then the terminal it had been launched from*, the subprocesses no longer had a terminal attached to their stdout, and would throw an IOError. Hope this helps you.
*NB: it must be done in this order. If you just kill the terminal, (for some reason) that would kill both the main program and the subprocesses.
I just got this error because the directory where I was writing files to ran out of memory. Not sure if this is at all applicable to your situation.
I'm new here, so please forgive if I slip up a bit when it comes to the code detail.
Recently I was able to figure out what cause the I/O error of the print statement when the terminal associated with the run of the python script is closed.
It is because the string to be printed to stdout/stderr is too long. In this case, the "out" string is the culprit.
To fix this problem (without having to keep the terminal open while running the python script), simply read the "out" string line by line, and print line by line, until we reach the end of the "out" string. Something like:
while true:
ln=out.readline()
if not ln: break
print ln.strip("\n") # print without new line
The same problem occurs if you print the entire list of strings out to the screen. Simply print the list one item by one item.
Hope that helps!
The problem is you've closed the stdout pipe which python is attempting to write to when print() is called
This can be caused by running a script in the background using & and then closing the terminal session (ie. closing stdout)
$ python myscript.py &
$ exit
One solution is to set stdout to a file when running in the background
Example
$ python myscript.py > /var/log/myscript.log 2>&1 &
$ exit
No errors on print()
It could happen when your shell crashes while the print was trying to write the data into it.
For my case, I just restart the service, then this issue disappear. don't now why.
My issue was the same OSError Input/Output error, for Odoo.
After I restart the service, it disappeared.

Python error when using os.popen()

Well, I have a python script running on Mac OS X. Now I need to modify it to support updating my SVN working copy into a specified time. However, after learning I've found that SVN commands only support updating the working copy into a specified version.
So I write a function to grub the information from the command: svn log XXX, to find the corresponding version to the specified time. Here is my solution:
process=os.popen('svn log XXX')
print process.readline()
print process.readline()
process.close()
To make the problem simple, I just print the first 2 lines in the output. However, when I was executing the script, I got the error message: svn: Write error: Broken pipe
I think that the reason why I got the message is that the svn command kept executing when I was closing the Popen. So the error message arise.
Is there any one who can help me slove the problem? Or give me a alternative solution to reach the goal. Thx!
I get that error whenever I use svn log | head, too, it's not Python specific. Try something like:
from subprocess import PIPE, Popen
process = Popen('svn log XXX', stdout=PIPE, stderr=PIPE)
print process.stdout.readline()
print process.stdout.readline()
to suppress the stderr. You could also just use
stdout, stderr = Popen('svn log XXX | head -n2', stdout=PIPE, stderr=PIPE, shell=True).communicate()
print stdout
Please use pysvn. It is quite easy to use. Or use subprocess.
Does you error still occur if you do finally:
print process.read()
And it is better to call wait() if you use os.popen or subprocess.

Categories

Resources