I am try to execute below command using python subprocess but it is failing.
Please help
import subprocess
cmd = "bash /opt/health_check -t 2>/dev/null"
retcode = subprocess.call([cmd])
print retcode
I am getting below output:
Traceback (most recent call last):
File "./script.py", line 65, in <module>
retcode = subprocess.call([cmd])
File "/usr/lib64/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib64/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib64/python2.7/subprocess.py", line 1335, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
If you call check_output with a list, you would need to tokenize the command yourself, as in:
import subprocess
cmd = ["bash", "/opt/health_check", "-t"]
retcode = subprocess.call([cmd])
print retcode
This doesn't use a shell so you can't use input redirection. If you really want to execute your command with a shell, then pass a string and set shell=True:
import subprocess
cmd = "bash /opt/health_check -t 2>/dev/null"
retcode = subprocess.call(cmd, shell=True)
print retcode
This is an incorrect way to call subprocess. A quick and dirty way to do it is to change it like:
subprocess.call(cmd, shell=True)
This will invoke the system's shell to execute the command, and you'll have access to all the goodies it provides. It's not something to use ligthly, however, so check security considerations from the docs before doing so.
Otherwise, you can simply provide the command as a list, like so:
subprocess.call(["bash", "/opt/health_check"])
Related
I am trying to read input from the user and store it in a variable by using subprocess.check_output in python2.7. But it shows up the error OSError: [Errno 2] No such file or directory when I try to run it. Also it is to be noted that I strictly want to use shell=False because of the security concerns.
I have tried subprocess.Popen and it doesnt work that way too.
I have tried to use sys.stdin = open('/dev/tty', 'r') and stdin=subprocess.PIPE but give the same error as above.
>>> import sys
>>> import subprocess
>>> sys.stdin = open('/dev/tty', 'r')
>>> cmd = ('read userinput && echo "$userinput"')
>>> confirmation = subprocess.check_output(cmd.split(), stdin=sys.stdin).rstrip()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 567, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
The expected result is that it should ask for user input and store it to the confirmation variable
You are entering a shell command (read and echo are shell built-ins, and && is shell syntax), therefore you need shell=True. This is a single shell command, so you don't use the split. The parentheses around the command in python have no effect in this case:
import sys
import subprocess
sys.stdin = open('/dev/tty', 'r')
cmd = 'read userinput && echo "$userinput"'
confirmation = subprocess.check_output(cmd, stdin=sys.stdin, shell=True).rstrip()
print'****', confirmation
Gives:
$ python gash.py
hello
**** hello
I have to print bash history using subprocess package.
import subprocess
co = subprocess.Popen(['history'], stdout = subprocess.PIPE)
History = co.stdout.read()
print("----------History----------" + "\n" + History)
but they prompt an error
Traceback (most recent call last):
File "test.py", line 4, in <module>
co = subprocess.Popen(['history'], stdout = subprocess.PIPE)
File "/usr/lib/python2.7/subprocess.py", line 394, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1047, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Normally, you would need to add shell=True argument to your Popen call:
co = subprocess.Popen(['history'], shell=True, stdout = subprocess.PIPE)
Or to manually specify the shell you want to call.
co = subprocess.Popen(['/bin/bash', '-c', 'history'], stdout = subprocess.PIPE)
Unfortunately, in this particular case it won't help, because bash has empty history when used non-interactively.
A working solution would be to read ${HOME}/.bash_history manually.
Kit is correct, reading ~/.bash_history may be a better option:
from os.path import join, expanduser
with open(join(expanduser('~'), '.bash_history'), 'r') as f:
for line in f:
print(line)
I made an attempt at parsing running programs in my computer (Debian OS) with the Subprocess python module. Here is my code:
import subprocess
cmd = "ps -A" # Unix command to get running processes
runningprox = subprocess.check_output(cmd) #returns output as byte string
rpstring = runningprox.decode("utf-8")
#converts byte string to string and puts it in a variable
print(rpstring)
However, when I run the code, I get the following error message:
Traceback (most recent call last): File "ratalert.py", line 6, in
runningprox = subprocess.check_output(cmd) #returns output as byte string File "/usr/local/lib/python3.6/subprocess.py", line 336, in
check_output
**kwargs).stdout File "/usr/local/lib/python3.6/subprocess.py", line 403, in run
with Popen(*popenargs, **kwargs) as process: File "/usr/local/lib/python3.6/subprocess.py", line 707, in init
restore_signals, start_new_session) File "/usr/local/lib/python3.6/subprocess.py", line 1333, in _execute_child
raise child_exception_type(errno_num, err_msg) FileNotFoundError: [Errno 2] No such file or directory: 'ps -A'
I don't understand why I get this error message. Considering 'ps -A' is neither a file nor a directory, but just the Unix command I put in a variable as a string.
How can I fix this? Thank you.
The subprocess.check_output function expects a list with the command and its arguments, like so:
runningprox = subprocess.check_output(['ps', '-A'])
Otherwise, it will treat the string you passed as a single command, and will look up for an executable file with name ps -A, space included and all.
You can use shlex to do the splitting as the shell would do:
import shlex, subprocess
cmd = 'ps -A'
runningprox = subprocess.check_output(shlex.split(cmd))
I am running into following error when trying to run a command using Popen,what is wrong here?
cmd = "export COMMANDER_SERVER=commander.company.com"
Pipe = Popen(cmd, stdout=PIPE, stderr=PIPE)
(output, error) = Pipe.communicate()
Error:-
Traceback (most recent call last):
File "test_ectool.py", line 26, in <module>
main()
File "test_ectool.py", line 13, in main
Pipe = Popen(cmd, stdout=PIPE, stderr=PIPE)
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
You need to separate the arguments from the command and give a list to Popen.
As Kenster's comment said, even if your command worked, you would only succeed in modifying an environmental variable inside a sub-shell not the main shell.
You will not be able run run export this way, because it is not a program. It is a bash built-in.
Here is an example of a command that does work, with the correct semantics.
from subprocess import Popen,PIPE
cmd = "echo COMMANDER_SERVER=commander.company.com"
Pipe = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)
(output, error) = Pipe.communicate()
print output
merlin2011's answer is incorrect regarding the command string for Popen (point #1). From the Python docs:
args should be a sequence of program arguments or else a single string.
As other people have stated, the environment variable will not be saved. For that, you need to use os.environ['VARNAME'] = value. If you want to use other bash builtins, then you must pass shell=True as an argument to Popen.
I have the following code that is attempting to start each of the "commands" below in Linux. The module attempts to keep each of the 2 commands running if either should crash for whatever reason.
#!/usr/bin/env python
import subprocess
commands = [ ["screen -dmS RealmD top"], ["screen -DmS RealmD top -d 5"] ]
programs = [ subprocess.Popen(c) for c in commands ]
while True:
for i in range(len(programs)):
if programs[i].returncode is None:
continue # still running
else:
# restart this one
programs[i]= subprocess.Popen(commands[i])
time.sleep(1.0)
Upon executing the code the following exception is thrown:
Traceback (most recent call last):
File "./marp.py", line 82, in <module>
programs = [ subprocess.Popen(c) for c in commands ]
File "/usr/lib/python2.6/subprocess.py", line 595, in __init__
errread, errwrite)
File "/usr/lib/python2.6/subprocess.py", line 1092, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
I think I'm missing something obvious, can anyone see what's wrong with the code above?
Use ["screen", "-dmS", "RealmD", "top"] instead of ["screen -dmS RealmD top"].
Maybe also use the complete path to screen.
Only guess is that it can't find screen. Try /usr/bin/screen or whatever which screen gives you.
The problem is that your command should be split. subprocces requires that the cmd is a list, not a string.
It shouldn't be:
subprocess.call('''awk 'BEGIN {FS="\t";OFS="\n"} {a[$1]=a [$1] OFS $2 FS $3 FS $4} END
{for (i in a) {print i a[i]}}' 2_lcsorted.txt > 2_locus_2.txt''')
That won't work. If you feed subprocess a string, it assumes that that is the path to the command you want to execute. The command needs to be a list. Check out http://www.gossamer-threads.com/lists/python/python/724330. Also, because you're using file redirection, you should use subprocess.call(cmd, shell=True). You can also use shlex.
I got same error when i wrote like this :-
subprocess.Popen("ls" ,shell = False , stdout = subprocess.PIPE ,stderr = subprocess.PIPE)
And problem is solved when i made shell=True .It will work
subprocess.Popen("ls" ,shell = False , stdout = subprocess.PIPE ,stderr = subprocess.PIPE, shell=True)
commands = [ "screen -dmS RealmD top", "screen -DmS RealmD top -d 5" ]
programs = [ subprocess.Popen(c.split()) for c in commands ]
Just in case.. I also got stuck with this error and the issue was that my files were in DOS instead of UNIX so at :
return subprocess.call(lst_exp)
where lst_exp is a list of args, one of them was "not found" because it was in DOS instead of UNIX but error thrown was the same :
File "/var/www/run_verifier.py", line 59, in main
return subprocess.call(lst_exp)
File "/usr/lib/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1335, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory