reading terminal in python not the same [duplicate] - python

This question already has answers here:
subprocess wildcard usage
(3 answers)
Closed 3 years ago.
import os
from subprocess import PIPE,Popen
#os.chdir("..")
cmd=["ls","*.py"]
try:
p=Popen(cmd,stdout=PIPE,universal_newlines=True,shell=True)
except Exception as e:
print(f"Exception:\t{e}")
for line in p.stdout:
print(line,end=" ")
p.stdout.close()
return_code=p.wait()
I am trying to get ls all python files in my server, however whenever I am writing the output which should be all .py files only, I am getting every file there, what am I doing wrong.
I tried ls *.py in server terminal and it works fine,however in script not working

You can directly use "ls *.py" as a command
import os
from subprocess import PIPE,Popen
#os.chdir("..")
cmd=["ls *.py"]
try:
p=Popen(cmd,stdout=PIPE,universal_newlines=True,shell=True)
except Exception as e:
print(f"Exception:\t{e}")
for line in p.stdout:
print(line,end=" ")
p.stdout.close()
return_code=p.wait()

Related

How to suppress stdout & stderr until success in python? [duplicate]

This question already has answers here:
Redirect subprocess stderr to stdout
(2 answers)
Closed 2 years ago.
I want to repeat block of codes until successful output but want to display only successful messages.
while i < 6:
try:
sys.tracebacklimit = 0 #this line seems not work
gluster_volume_names = []
gstatus_output = subprocess.check_output('gstatus -a -o json ', shell=True).decode()
date, time, json_part = gstatus_output.split(maxsplit=2)
gluster_info = json.loads(json_part)
volume_list = gluster_info["volume_summary"]
....
....
break
except:
i += 1
continue
But I don't know how to suppress these output below. (unsuccessful run) They are not the outcome I want. The block of code eventually ran successfully after less than 5 tries then exit.
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/gstatus-0.66-py3.6.egg/EGG-INFO/scripts/gstatus", line 143, in main
File "/usr/local/lib/python3.6/site-packages/gstatus-0.66-py3.6.egg/gstatus/libgluster/cluster.py", line 543, in update_state
gstatus.libutils.excepts.GlusterFailedVolume: Unable to query volume 'BLAH'
Possible cause: cluster is currently reconverging after a nodehas entered a disconnected state.
Response: Rerun gstatus or issue a peer status command to confirm
Please help!
Instead of using subprocess.check_output, you should use the standard subprocess.run method and pipe the standard error to /dev/null. Use the following instead:
gstatus_output = subprocess.run('gstatus -a -o json ', shell=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode()
If you just want to suppress the errors in the console on a linux-system you can try:
python yourCode.py 2>/dev/null
With this you can also suppress stdout:
python yourCode.py 1>/dev/null
One possibility is to redirect standard output and standard error to a string. After execution, you can choose whether to print the results of the string, or discard it and try again.
from contextlib import redirect_stdout, redirect_stderr
import io
f = io.StringIO()
with redirect_stdout(f):
with redirect_stderr(f):
.... whatever you want ....
s = f.getvalue()

subprocess.run not able to print output of multiple lines in a file [duplicate]

This question already has answers here:
Get java version number from python
(6 answers)
Closed 3 years ago.
I am using subprocess.run to run a command and print output to a file.
I am able to print correct output for 'python --version' since the answer is 'Python 3.6.5', but when i run the same command for 'java -version' there is no output in text file, but it is reflected in console.
Maybe it's because the output of 'java -version' is spread in three lines!
import subprocess
import os
import sys
sys.stdout = open('outputCS.txt','wt')
result = subprocess.run('python --version', stdout=subprocess.PIPE)
print(result.stdout.decode('utf-8'))
import subprocess
f = open("stuff", "wt")
subprocess.run(['python', '--version'], stdout=f, stderr=f)
subprocess.run(['java', '-version'], stdout=f, stderr=f)

Supress OS command prompt popup in python [duplicate]

This question already has answers here:
Suppressing output in python subprocess call [duplicate]
(2 answers)
Get output of system ping without printing to the console
(2 answers)
Closed 5 years ago.
import subprocess, platform
def ping(host):
args = "ping -n 1 " + host
return subprocess.call(args) == 0
print(ping("www.google.com"))
I am using this code in order to ping a website to test whether it is up or down, which works perfectly, however it results in a command prompt window briefly appearing which is not ideal for what I am working on, so my question is;
How can I supress this window from appearing on pings requests (windows based solution needed)
To use ping to know whether an address is responding, use its return value, which is 0 for success. subprocess.check_call will raise and error if the return value is not 0. To suppress output, redirect stdout and stderr. With Python 3 you can use subprocess.DEVNULL rather than opening the null file in a block.
import os
import subprocess
with open(os.devnull, 'w') as DEVNULL:
try:
subprocess.check_call(
['ping', '-c', '3', '10.10.0.100'],
stdout=DEVNULL, # suppress output
stderr=DEVNULL
)
is_up = True
except subprocess.CalledProcessError:
is_up = False
Ref:Get output of system ping without printing to the console

How to check if subprocess terminated properly? [duplicate]

This question already has answers here:
Retrieving the output of subprocess.call() [duplicate]
(7 answers)
Closed 8 years ago.
I want to know if the subprocess.call() has terminated correctly without any error in the called function. For example, in the below code, if the path provided is not appropriate, the ls command gives an error as:
ERROR:No such file or directory.
I want same output to be stored as string.
import subprocess
path = raw_input("Enter the path")
subprocess.call(["ls","-l",path])
from subprocess import Popen, PIPE
p = Popen(["ls", "-l", path], stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate()
status = p.returncode
if status:
# something went wrong
pass
else:
# we are ok
pass
Although consider using os.listdir
You cannot do that with call, because what it does is only:
Run the command described by args. Wait for command to complete, then return the returncode attribute.
So you can only determine the return code of a program, which usually means zero if no error occurred, and non-zero otherwise.
Use the check_output method from the same module:
try:
result = subprocess.check_output(["ls", "-l", path],
stderr = subprocess.STDOUT)
print result
except subprocess.CalledProcessError, e:
print "Error:", e.output
Here is a working demo.

Python Script execute commands in Terminal [duplicate]

This question already has answers here:
Running Bash commands in Python
(11 answers)
Closed 9 months ago.
I read this somewhere a while ago but cant seem to find it. I am trying to find a command that will execute commands in the terminal and then output the result.
For example: the script will be:
command 'ls -l'
It will out the result of running that command in the terminal
There are several ways to do this:
A simple way is using the os module:
import os
os.system("ls -l")
More complex things can be achieved with the subprocess module:
for example:
import subprocess
test = subprocess.Popen(["ping","-W","2","-c", "1", "192.168.1.70"], stdout=subprocess.PIPE)
output = test.communicate()[0]
I prefer usage of subprocess module:
from subprocess import call
call(["ls", "-l"])
Reason is that if you want to pass some variable in the script this gives very easy way for example take the following part of the code
abc = a.c
call(["vim", abc])
import os
os.system("echo 'hello world'")
This should work. I do not know how to print the output into the python Shell.
Custom standard input for python subprocess
In fact any question on subprocess will be a good read
https://stackoverflow.com/questions/tagged/subprocess
for python3 use subprocess
import subprocess
s = subprocess.getstatusoutput(f'ps -ef | grep python3')
print(s)
You can also check for errors:
import subprocess
s = subprocess.getstatusoutput('ls')
if s[0] == 0:
print(s[1])
else:
print('Custom Error {}'.format(s[1]))
# >>> Applications
# >>> Desktop
# >>> Documents
# >>> Downloads
# >>> Library
# >>> Movies
# >>> Music
# >>> Pictures
import subprocess
s = subprocess.getstatusoutput('lr')
if s[0] == 0:
print(s[1])
else:
print('Custom Error: {}'.format(s[1]))
# >>> Custom Error: /bin/sh: lr: command not found
You should also look into commands.getstatusoutput
This returns a tuple of length 2..
The first is the return integer (0 - when the commands is successful)
second is the whole output as will be shown in the terminal.
For ls
import commands
s = commands.getstatusoutput('ls')
print s
>> (0, 'file_1\nfile_2\nfile_3')
s[1].split("\n")
>> ['file_1', 'file_2', 'file_3']
In python3 the standard way is to use subprocess.run
res = subprocess.run(['ls', '-l'], capture_output=True)
print(res.stdout)
The os.popen() is pretty simply to use, but it has been deprecated since Python 2.6.
You should use the subprocess module instead.
Read here: reading a os.popen(command) into a string
Jupyter
In a jupyter notebook you can use the magic function !
!echo "execute a command"
files = !ls -a /data/dir/ #get the output into a variable
ipython
To execute this as a .py script you would need to use ipython
files = get_ipython().getoutput('ls -a /data/dir/')
execute script
$ ipython my_script.py
You could import the 'os' module and use it like this :
import os
os.system('#DesiredAction')
Running: subprocess.run
Output: subprocess.PIPE
Error: raise RuntimeError
#! /usr/bin/env python3
import subprocess
def runCommand (command):
output=subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
if output.returncode != 0:
raise RuntimeError(
output.stderr.decode("utf-8"))
return output
output = runCommand ([command, arguments])
print (output.stdout.decode("utf-8"))

Categories