I need to run a command via rpyc and get the result of this command.
But whenever I run the command, it is printed on the remote server and can not bring the result.
What I am doing is the following:
import os, sys
import rpyc
conn = rpyc.classic.connect('server_remote')
a = conn.modules.os.system( "ls -lh")
print a
The output of my command is 0 for any command I run.
python get_output.py
0
Use os.popen or subprocess.checked_output instead of system. System just returns the exit code, while the output is printed to your stdout (i.e. you don't get hold of it programmatically)
Related
I am trying to port some simple scripts that I have in tcl to python.
Using tcl/expect, we can see every executed command on the standard output. For example,
spawn ssh admin#$IP
send "ls\r"
would yield by default an output like this:
ssh admin#10.10.10.10
ls
....
In python, only way I saw was to decode the child.before or after outputs.
Is there a way python can output everything it runs to the console or a file ?
This is what I am doing now:
#!/usr/bin/env python3
import pexpect
shellprompt = "] # "
child = pexpect.spawn('ssh admin#XYZ')
child.sendline('ls')
child.expect(shellprompt)
ls_out = child.before.decode()
print(ls_out)
This is run on a Linux machine, and doing ssh to a Linux machine
From a bash function, I want to call a python script which prompts for input, and I need to run that script as a module using python -m
Here is select_pod.py
# above this will be a print out of pods
pod = input('Pick pod')
print(pod)
Here is the bash function:
function foo() {
POD=$(python3 -m select_pod)
kubectl exec $POD --stdin --tty bash
}
I can't get the input to work, i.e. "Pick pod" is not printed to the terminal.
When you do POD=$(python3 -m select_pod), the POD=$(...) means that any output printed to stdout within the parentheses will be captured within the POD variable instead of getting printed to the screen. Simply echoing out POD is no good, as this will first be done once the Python script has finished.
What you need to do is to duplicate the output of the Python program. Assuming Linux/Posix, this can be done using e.g.
POD=$(python3 -m select_pod | tee /dev/stderr)
Because your terminal shows both stdout and stderr, duplicating the output from stdout to stderr makes the text show up.
Hijacking the error channel for this might not be ideal, e.g. if you want to later sort the error messages using something like 2> .... A different solution is to just duplicate it directly to the tty:
POD=$(python3 -m select_pod | tee /dev/tty)
You can change sys.stdout before input :
import sys
save_sys_stdout = sys.stdout
sys.stdout = sys.stderr
pod = input('Pick pod')
sys.stdout = save_sys_stdout
print(pod)
So that POD=$(python3 -m select_pod) will work and you don't need to do split after.
I am trying to write the codes to run a C executable using Python.
The C program can be run in the terminal just by calling ./myprogram and it will prompt a selection menu, as shown below:
1. Login
2. Register
Now, using Python and subprocess, I write the following codes:
import subprocess
subprocess.run(["./myprogram"])
The Python program runs but it shows nothing (No errors too!). Any ideas why it is happening?
When I tried:
import subprocess
subprocess.run(["ls"])
All the files in that particular directory are showing. So I assume this is right.
You have to open the subprocess like this:
import subprocess
cmd = subprocess.Popen(['./myprogram'], stdin=subprocess.PIPE)
This means that cmd will have a .stdin you can write to; print by default sends output to your Python script's stdout, which has no connection with the subprocess' stdin. So do that:
cmd.stdin.write('1\n') # tell myprogram to select 1
and then quite probably you should:
cmd.stdin.flush() # don't let your input stay in in-memory-buffers
or
cmd.stdin.close() # if you're done with writing to the subprocess.
PS If your Python script is a long-running process on a *nix system and you notice your subprocess has ended but is still displayed as a Z (zombie) process, please check that answer.
Maybe flush stdout?
print("", flush=True,end="")
Im trying to use ubuntu terminal through python script.
The script receives the command text(from input() for test), sends it to the terminal, the terminal return the result of the command, script print result in a console.
I already get that I should use subprocess Popen and PIPE, but after inputing 1st command, script print only b'', after 2nd raise error "ValueError: Cannot send input after starting communication"
my test code(yes, its bad):
import subprocess as sb
from subprocess import PIPE, Popen
p=Popen(['gnome-terminal'],stdout=PIPE,stdin=PIPE,stderr=PIPE)
command = 'cmd'
while True:
command = input()
out_data, err_data = p.communicate(command.encode())
print(repr(out_data))
I know I do it in a wrong way, but can't find right. Sorry for English.Thanks.
You can do this using the os module:
#!/usr/bin/env python
import os
output = os.listdir('path_to_folder') # output is a list
# Do whatever you want to output
You can read more about what else the os module can do at https://docs.python.org/3/library/os.html. Note that the methods in the module are portable across different OSes, so you can in fact use your script outside Ubuntu.
I am trying to execute an ansible-playbook commend in subprocess at the end of a python script, which does 'magic' before kicking off the correct command.
If you are not familiar with ansible-playbook. The output is normally colorful(green/yellow/red text) and is correctly spaced.
I would be fine if python just kicked off a command and exited if need be.
What I am getting currently is black and white text after the command has completed.
I want to get the normal color outout in real time as if I ran ansible-playbook from the command line. Is there a way to do this?
my current code is as follows:
command = '{0} --flush-cache -f 20 -i {1}/dyn_inv.py --extra-vars #{2}/vars.json {3}'.format(ansible_playbook_loc, script_path, var_path, args.playbook[0])
print command
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
devices = process.communicate()[0].rstrip('\n').split()
print devices
Ansible by default will only colorize text when its output is connected to a terminal. You can force it to use color codes by setting ANSIBLE_FORCE_COLOR=1 in the environment. For example:
import os
os.environ['ANSIBLE_FORCE_COLOR'] = '1'
You can accomplish the same thing by setting the force_color option in your ansible.cfg.