Convert Command To Subprocess - python

I currently have the following:
tf = Terraform()
tf.init()
tf.plan(capture_output=False)
approve = {"auto-approve": True}
print(tf.apply(capture_output=False, auto_approve=True, skip_plan=True,**approve))
This works quite well, but I need to put it into a subprocess. I've tried the following:
tf = Terraform()
tf.init()
tf.plan(capture_output=False)
approve = {"auto-approve": True}
subprocess.check_output(['tf.apply','capture_output','0', 'auto_approve','1', 'skip_plan','1','**approve'])
However, I receive the error: "'tf.apply' is not recognised as an internal or external command, operable program or batch file."
Can I convert the above into a subprocess? And if so, how?

subprocess executes external commands. By contrast, you are trying to execute something like (but not quite) Python code. This fundamentally can’t work.
What you can do is create a Python script that contains your Terraform code and execute that via subprocess.check_output. However, this only works if the Python script is complete. You can’t jus execute a fragment as in your case.
For a minimal example of what you can do, take your original script, save it as tf.py and execute it like this in Python:
subprocess.check_output(['python', 'tf.py'])

Related

Opening a command window and passing content to it using Python

I am currently working with a software package that allows you to create Python scripts and execute them from inside that package. The results of any script are saved back into the program. When the script executes, it does not show a command prompt window.
Is there an easy way to open a command prompt window from inside the script and pass over information for display, such as a dataframe header, a string or a list of values?
I have found from earlier SO posts that I can use:
import os
os.system('cmd /k "Some random text"')
This works as expected, but when I use the following code:
x = str(2 * 2)
output= f'cmd /k "{x}"'
os.system(output)
The number 4 is passed to the command window, but the following message appears:
'4' is not recognized as an internal or external command, operable program or batch file.
The answer is in the question.
'4' is not recognized as an internal or external command, operable program or batch file.
Open cmd and type anything it will give error unless we type something which is recognized by cmd. e.g a help command.
if there is something we want to type in cmd and let it get processed/printed on console we use a command
echo
in your program only the echo command was missing, which will let your output get printed on cmd.
Last but not the least, always remember the ZEN of Python
Use subprocess instead
The `subprocess` has some more benefits compared to `Os`:
The subprocess module provides a consistent interface to creating and working with additional processes.
It offers a higher-level interface than some of the other available modules, and is intended to replace functions such as os.system(), os.spawn*(), os.popen*(), popen2.*() and commands.*().
Reference
If you want to write something like to print 4 in another cmd tab, do like this:
import subprocess
var = '4'
subprocess.Popen(['start','cmd','/k','echo',var], shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE, text = True)
Result:
It opens another cmd tab and passes a command such as echo var.

Problems with redirected stdin and stdout when using py in matlab to run python code

I have some python code that runs perfectly when run within python. When I run the code from within matlab using py I appear to have problems with the redirection of stdin and stdout.
The problem can be illustrated with the python code in a file ztest.py:
import os
def ztest():
os.system(f'./jonesgrid > /dev/null < zxcvbn-split-08.txt')
When run within python, all is well:
>>> import ztest
>>> ztest.ztest()
>>>
When this is run from matlab with the command
>> py.ztest.ztest()
I get the following output:
At line 283 of file jonesgrid.for (unit = 5, file = 'fort.5')
Fortran runtime error: End of file
Error termination. Backtrace:
#0 0x2aaaaacead1a
<other lines cut>
The file fort.5 has been created together with fort.6. Normally these two files are associated with standard input and output respectively and are not created in the run. I have also tried using subprocess.run() and get the same problem.
I'm not sure whether this should be posted in a python forum or a matlab one, but I'm guessing the problem lies with the way in which matlab is interfacing with python. Other parts of my code that use os.system() that don't make use of redirection work fine.

Some functions from library works in python shell but not in a script

I'm having trouble getting certain functions from a library called art (https://github.com/sepandhaghighi/art) to run in a script, though they work fine in a shell. The script/commands entered sequentially look like this:
from art import *
randart() <(function fails in script, but succeeds in shell)
tart("test") <(different function, same library, succeeds in both shell and script)
import sys
print(sys.version)
The python version is 3.7.5 for both the shell and the script. The first function does not throw an error when run in a script, but does not give any output. Its desired output is a random ascii_art from a collection. I feel like I'm missing something really simple. Any ideas? The documentation on github reports "Some environments don't support all 1-Line arts", however they are the same python version on the same machine. Are there other portions of the environment that could be the cause?
You need to print randart() while writing in script. Make a habit of using print() for everything while printing. Shell is the place which returns the value by default whereas you need to tell the script window what to do with any name or function.
so use this:
from art import *
print(randart())
in the shell it is implicitly printed ... in a script you must explicitly
print(randart())

How to run External collector from Scollector?

I am trying to run external sample.py script in /path-to-scollector/collectors/0 folder from scollector.
scollector.toml:
Host = "localhost:0"
ColDir="//path-to-scollector//collectors//"
BatchSize=500
DisableSelf=true
command to run scollector:
scollector-windows-amd64.exe -conf scollector.toml -p
But I am not getting the sample.py metrics in the output. It is expected to run continuosly and print output to cnosole. Also when I am running:
scollector-windows-amd64.exe -conf scollector.toml -l
my external collector is not listed.
In your scollector.toml, You should one line as below,
Filter=["sample.py "] .
in your sample.py, you need this line
#!/usr/bin/python
For running scollector on linux machine the above solution works well. But with windows its a bit tricky. Since scollector running on windows can only identify batch files. So we need to do a little extra work for windows.
create external collector :-
It can be written in any language python,java etc. It contains the main code to get the data and print to console.
Example my_external_collector.py
create a wrapper batch script :-
wrapper_external_collector.bat.
Trigger my_external_collector.py inside wrapper_external_collector.bat.
python path_to_external/my_external_collector.py
You can pass arguments to the script also.Only disadvantage is we need to maintain two scripts.

execute python file in batch mode by specifying the list of commands

I got a python file which is a code that I developed. During his execution I input from the keyboard several characters at different stages of the program itself. Also, during the execution, I need to close a notepad session which comes out when I execute into my program the command subprocess.call(["notepad",filename]). Having said that I would like to run this code several times with inputs which change according to the case and I was wondering if there is an automatic manner to do that. Assuming that my code is called 'mainfile.py' I tried the following command combinations:
import sys
sys.argv=['arg1']
execfile('mainfile.py')
and
import sys
import subprocess
subprocess.call([sys.executable,'mainfile.py','test'])
But it does not seem to work at least for the first argument. Also, as the second argument should be to close a notepad session, do you know how to pass this command?
Maybe have a look at this https://stackoverflow.com/a/20052978/4244387
It's not clear what you are trying to do though, I mean the result you want to accomplish seems to be just opening notepad for the sake of saving a file.
The subprocess.call() you have is the proper way to execute your script and pass it arguments.
As far as launching notepad goes, you could do something like this:
notepad = subprocess.Popen(['notepad', filename])
# do other stuff ...
notepad.terminate() # terminate running session

Categories

Resources