Run powershell module from python in ubuntu - python

I have PowerShell installed on ubuntu 20.04 and I want to do the following steps from the python script:
Invoke it
Import PowerShell module
Run Powershell module several times
From the terminal, I would do it as:
pwsh
Import-Module ./MyModule.psd1
MyModule -param 'param_val' -Quiet > filename several times
I was trying to use
p = subprocess.Popen("pwsh", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, universal_newlines=True)
time.sleep(2)
p.stdin.write("Import-Module ./MyModule.psd1")
#in loop
p.stdin.write("MyModule -param 'param_val' -Quiet > filename")
Which is obviously not working. I tried to use Thread and Queue but I am afraid that the problem is not in it.
I would be extremely grateful for any help and suggestions.

Related

How to Run a Specific Powershell Command Within Python with a Defined Variable and Print Output?

I am trying to run a specific command from Python to Powershell:
The command works as expected in Powershell. The command in Powershell is as following:
gpt .\Method\gpt_scripts\s1_cal_deb.xml -t .\deburst\S1A_IW_SLC__1SDV_20180909T003147_20180909T003214_023614_0292B2_753E_Cal_deb_script.dim .\images\S1A_IW_SLC__1SDV_20180909T003147_20180909T003214_023614_0292B2_753E.zip
Powershell Output:
os.getcwd()
'C:\\Users\\Ishack\\Documents\\Neta-Analytics\\Harvest Dates\\S1_SLC_Processing'
The current directory is the same as in PowerShell
I tried something like this:
import subprocess
process = 'gpt .\Method\gpt_scripts\s1_cal_deb.xml -t .\deburst\S1A_IW_SLC__1SDV_20180909T003147_20180909T003214_023614_0292B2_753E_Cal_deb_script.dim .\images\S1A_IW_SLC__1SDV_20180909T003147_20180909T003214_023614_0292B2_753E.zip'
process = subprocess.Popen(['powershell.exe', '-NoProfile', '-Command', '"&{' + process + '}"'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process
Output:
<subprocess.Popen at 0x186bb202388>
But when I press enter I get no response, I would like Python to print out the output just like in Powershell. I researched other similar questions but still no solution to the problem.
Thanks,
Ishack
import os
os.system("powershell.exe -ExecutionPolicy Bypass -File .\SamplePowershell.ps1")
SamplePowershell.ps1
Write-Host "Hello world"
hostname
This worked for me. Commands in file SamplePowershell.ps1.
and if you want to use subprocess
import subprocess
k=subprocess.Popen('powershell.exe hostname', stdout=subprocess.PIPE, stderr=subprocess.PIPE);
print(k.communicate())

Python: get stdout from background subprocess

i'm trying to get informations of a network interface on a linux machine with a python script, i.e. 'ifconfig -a eht0'. So i'm using the following code:
import subprocess
proc = subprocess.Popen('ifconfig -a eth0', shell=True, stdout=subprocess.PIPE)
proc.wait()
output = proc.communicate()[0]
Well if I execute the script from terminal with
python myScript.py
or with
python myScript.py &
it works fine, but when it is run from background (launched by crontab) without an active shell, i cannot get the output.
Any idea ?
Thanks
Have you tried to used "screen"?
proc = subprocess.Popen('screen ifconfig -a eth0', shell=True, stdout=subprocess.PIPE)
I'm not sure that it can work or not.
Try proc.stdout.readline() instead of communicate, also stderr=subprocess.STDOUT in subprocess.Popen() might help. Please post the results.
I found a solution to the problem, i guess that the system is not able to recognize the function ifconfig when executed by the crontab. So adding the full path to the subprocess allows the script to be executed properly:
`proc = subprocess.Popen('/sbin/ifconfig -a eth0',shell=True,stdout=subprocess.PIPE)
proc.wait()
output = proc.communicate()[0]`
and now i can manage the output string.
Thanks

Use python to run multiple commands inside the wine cmd?

Using python I can get either of these to work:
subprocess.call(['wine', 'cmd'])
os.system("wine cmd")
I'm using Ubuntu and python 3.5, Once I get into the wine cmd prompt I can no longer run commands, non of the ways to run multiple commands that I have seen online work, they don't error out, it just opens the cmd and pauses, I think it treats the cmd once open as a running command and is waiting to move on to the next command which it assumes is for the shell not the wine cmd, how can i then run commands inside the wine cmd once opened?
edit: Basically any time I run a command that requires further user input from within that command, how do I interact inside of that command?
You could build up from DOS through BASH to python as in the example code here. I cut and paste the code into python 2.7 and it worked, but you might like to confirm on 3.5
If you specifically need interaction rather than just running a DOS command then you could use subprocess.Popen.communicate to interact with your script which then interacts with wine/dos.
import subprocess, os, stat
from subprocess import Popen
from subprocess import PIPE
from subprocess import check_output
command_script="/tmp/temp_script.sh"
f1 = open(command_script,'w')
f1.write("#!/bin/bash\n")
#to run a dos command
#f1.write(r'WINEPREFIX=/path/tp/wine/prefix wine cmd /c #mydoscommand argval1'+'\n')
#for example
f1.write(r'wine cmd /c #echo Hello_world'+'\n')
#or to run a specifically pathed executable
#f1.write(r'WINEPREFIX=/path/tp/wine/prefix wine "c:\\Program Files (x86)\\path\\to\\executable.exe" additionalargs '+'\n')
f1.close()
st = os.stat(command_script)
os.chmod(command_script, st.st_mode | stat.S_IEXEC)
p = Popen(command_script, stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate(b"input data that is passed to subprocess' stdin")
rc = p.returncode
print output
os.remove(command_script)
Have a look at the answers where I nicked some of the code from Running windows shell commands with python and calling-an-external-command-in-python

Opening a terminal running the same program in Python

I am familiar with how to open a terminal from Python (os.system("gnome-terminal -e 'bash -c \"exec bash\"'")), but is there a way to open another terminal running the same program that opened the new terminal?
For instance, if I was running a program called foo.py and it opened another terminal, the new terminal would also be running foo.py.
See this question, it's pretty close. You want to add sys.argv as a parameter, though:
import sys
import subprocess
cmd = 'xterm -hold -e ./{0}'.format(' '.join(sys.argv))
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Be sure you somehow check how many processes/terminals you run already, otherwise it will hang your machine in a matter of seconds.

Running a bash script from Python

I need to run a bash script from Python. I got it to work as follows:
import os
os.system("xterm -hold -e scipt.sh")
That isn't exactly what I am doing but pretty much the idea. That works fine, a new terminal window opens and I hold it for debugging purposes, but my problem is I need the python script to keep running even if that isn't finished. Any way I can do this?
I recommend you use subprocess module: docs
And you can
import subprocess
cmd = "xterm -hold -e scipt.sh"
# no block, it start a sub process.
p = subprocess.Popen(cmd , shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# and you can block util the cmd execute finish
p.wait()
# or stdout, stderr = p.communicate()
For more info, read the docs,:).
edited misspellings

Categories