How do I print the output of the exec() function in python 3.5? - python-3.x

How do I have it so that you pass in a python command to the exec() command, waits for completion, and print out the output of everything that just happened?
Many of the code out there uses StringIO, something that is not included in Python 3.5.

You can't. Exec just executes in place and returns nothing. Your best bet would be to write the command into a script and execute it with subprocess if you really want to catch all the output.
Here's an example for you:
#!/usr/bin/env python3
from sys import argv, executable
from tempfile import NamedTemporaryFile
from subprocess import check_output
with NamedTemporaryFile(mode='w') as file:
file.write('\n'.join(argv[1:]))
file.write('\n')
file.flush()
output = check_output([executable, file.name])
print('output from command: {}'.format(output))
And running it:
$ ./catchandrun.py 'print("hello world!")'
output from command: b'hello world!\n'
$

Related

Program ran from subprocess.run() in python3, cannot create files

I have a program that is supposed to create a text file. When called from subprocess.run() in python3, the program runs but it does not create the text file. The program works as expected when called from the terminal.
import subprocess as subp
...
comm=[os.getcwd()+'/test/myprogram.bin','arg1','arg2']
compl_proc = subp.run(comm,
capture_output=True,
text=True,
check=True)
The file was in the python script directory, because I never told subprocess.run() what is the current working directory of the subprocess. So cwd='...' is added.
import subprocess as subp
import os
...
comm=[os.getcwd()+'/test/myprogram.bin','arg1','arg2']
compl_proc = subp.run(comm,
cwd=os.getcwd()+'/test/',
capture_output=True,
text=True,
check=True)

How to get command's standard output with subprocess?

For some reason, I want to gather the help message of some commands. In order to do it, I use the subprocess module in Python3. My code works fine for linux commands but not when I use it on BASH commands. Typically I want it to work on the cd BASH command.
Here is the snippet of code I use for now:
import subprocess
instruction = ["cat", "--help"]
proc = subprocess.run(instruction, stdout=subprocess.PIPE,stderr=subprocess.PIPE, universal_newlines=True)
return proc.stdout
As said before, it works fine and it returns the help message of the command cat.
Here is what it returns when I try to adapt my code in order to handle BASH commands:
>>> import subprocess
>>> subprocess.run("cd --help", shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE).stdout
b''
My question is simple, is it possible to get BASH commands' help message using Python3. If so, how to do that ?
You can take a look at what subprocess.run returns:
>>> import subprocess
>>> result = subprocess.run("cd --help", shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
>>> result
CompletedProcess(args='cd --help', returncode=1, stdout=b'', stderr=b'/bin/sh: line 0: cd: --: invalid option\ncd: usage: cd [-L|-P] [dir]\n')
Turns out, cd --help is an error:
$ cd --help
-bash: cd: --: invalid option
cd: usage: cd [-L|-P] [dir]
So you should look for it in result.stderr.

isatty() always returning False?

I want to pipe data via stdin to a Python script for onwards processing. The command is:
tail -f /home/pi/ALL.TXT | python3 ./logcheck.py
And the Python code is:
import sys
while 1:
if (sys.stdin.isatty()):
for line in sys.stdin:
print(line)
I want the code to continuously watch stdin and then process each row when received. The tail command is working when run on its own but the python script never outputs anything.
Checking isatty() it appears to always return False?
Help!
A TTY is when you use your regular terminal - as in opening up a python in your shell, and typing
BASH>python
>>>from sys import stdin
>>>stdin.isatty() #True
In your case the standard input is coming from something which is not a tty. Just add a not in the if statement.

How to write command using subprocess in python3

import subprocess
proc = subprocess.Popen(['systemctl', 'reload', 'postgresql-9.6.service'], stdout=subprocess.PIPE, shell=True)
(db_cmd, err) = proc.communicate()
print (db_cmd)
I am trying to run systemctl reload postgresql-9.6.service using python 3 but I am not able to get output. And I am getting output such as:
reload: systemctl: command not found
b''
First of all: read the docs: Subprocess module Python 3.
You mistyped the import statement: it should be: "import subprocess".
Use sudo to execute the program you wrote: sudo python /full/path/to/your/script.
Then: it is more pythonic if you write db_cmd = proc.communicate()[0] because in this way you create only the variable you use.
Finally, your error is indicating that something went wrong while you were processing the systemctl command. In particular it seems to be missing the reload command. Try using restart.
In addition: this question is a duplicate of How to use subprocess.

Can i access the variables of the python script after run that python script with console?

I run the python script using terminal command
python3 myScript.py
It's simply run my program but if i want to open python console after complete run of my script so that i can access my script's variables.
So, What should i do ? and How can i get my script's variables after run the code using terminal ?
Open a python terminal (type 'python' in cmd);
Paste this (replace 'myScript.py' with your script filename):
def run():
t = ""
with open('myScript.py') as f:
t = f.read()
return t
Type exec(run()). Now you will have access to the variables defined in myScript.py.
I needed to do this so I could explore the result of a request from the requests library, without having to paste the code to make the requests every time.
Make the program run the other program you want with the variables as arguments. For example:
#program1
var1=7
var2="hi"
import os
os.system("python %s %d %s" % (filename, var1, var2))
#program2
import sys
#do something such as:
print(sys.argv[1]) #for var1
print(sys.argv[2]) #for var2
Basically, you are running program2 with arguments that can be referenced later.
Hope this helps :)

Resources