How to run a powerShell script from a python file - python

I couldn't find much information on this unfortunately, but I wish to run a powerShell script from a python file I've written. I want the user to actually see the powerShell script being run and the user can enter inputs that the powerShell script requires from python. I am using pyCharm as an IDE.
When I run the script to call this powerShell script, it gives me this error:
File "C:\TestAutomation\eFuse\eFuse.ps1", line 19
SyntaxError: Non-ASCII character '\xc2' in file C:\Test\eK\eK.ps1 on line 19, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
Here is the relevant part of the code:
elif switch_result == "eTool":
subprocess.call(['python', 'C:\\TestAutomation\\eFuse\\eFuse.ps1'], stdout=sys.stdout)
This elif statement is a part of other if/elif statements that run other python files using the subproccess module, but for some reason I can't get this powerShell file to be run. Any advice is appreciated. Thank you

First, you should already know .py file's interpreter is python.exe
So, it's easy to understand .ps1 file's interpreter is powershell.exe, not python.exe
I just copy & paste from yours, your code should look like following,
subprocess.call('powershell.exe -File "C:\\TestAutomation\\eFuse\\eFuse.ps1"', stdout=sys.stdout)
Details about powershell.exe -?

You can do following for provide input from user to PS (powershell) script from python :
1) Create parameterised powershell script
2) Take input in python and set it as PS script parameter.
3) run/execute the script with given params.
Here is the sample to run powershell script from python with param. Its a python code :
* Hope you have the PS script with parameters.
import subprocess
params = ['param1', 'param2'] # POWERSHELL SCRIPT PARAMETERS ( optional )
script_path = "C:\\PowershellScripts\\test.PS1" # POWERSHELL SCRIPT PATH
commandline_options = ["Powershell.exe", '-ExecutionPolicy', 'Unrestricted', script_path] # INITIALIZING COMMAND
for param in params: # FOREACH LOOP OF PARAMETERS
commandline_options.append(param) # ADDING SCRIPT PARAMETERS TO THE COMMAND
result = subprocess.run(commandline_options, stdout = subprocess.PIPE, stderr = subprocess.PIPE, universal_newlines = True) # RUN THE SCRIPT USING SUBPROCESS WITH PARAMS
print(result.returncode) # PRINT THE RETURN CODE FROM POWERSHELL SCRIPT
print(result.stdout) # PRINT THE STANDARD OUTPUT FROM POWERSHELL SCRIPT
print(result.stderr) # PRINT THE STANDARD ERROR FROM POWERSHELL SCRIPT
You can see the output of python if it exist ( if there is no error in powershell script. you will not get any output from last line )

Related

subprocess.call command runs but doesn't actually do anything

I get no error message when running the following code, however it doesn't perform the required task (to be more precise, the output is an empty file).
import subprocess
chemin_in_troncon = r"C:\Users\HBT\Desktop\Run\1OUTIL_CREATION_DB\donnees_out\2-FAX0W0\FAX0W0900_2.in"
chemin_strapontin = r"C:\Users\HBT\Desktop\STRAPONTIN\strapontin9120.exe"
result900 = subprocess.call([chemin_strapontin, chemin_in_troncon], shell=True)
However, when I execute the equivalent task directly from the shell with the following command, the .exe file does its job and gives me a non-empty output :
strapontin9120.exe ../Run/1OUTIL_CREATION_DB/donnees_out/2-FAX0W0/FAX0W0900_2.in
Here, I wrote this shell command while in the directory containing "strapontin9120.exe".
Any idea what is wrong in my code?

How to run perl script with multiple args from python script

I made a python code that must sequentially execute a series of perl commands on the PC shell, the problem is that I did not realize that to send these scripts I have to add parameters (i have n_params), advice?
example command to send
perl [file_name.pl] [params]
To run these commands on the windows CMD I am using os and subprocess
python code example
# command = perl [file_name.pl] [params]
# path = location/of/where/the/pl/file/is/saved
perl_script = subprocess.Popen(["C:\\Perl64\\bin\\perl.exe",path + command], stdout=sys.stdout)
perl_script.communicate()
But running the script like this, the code gets me wrong because it says it can't find the filename in the specific directory
This argument to Popen()
["C:\\Perl64\\bin\\perl.exe", path + command]
does not look correct since you wrote that command is perl [file_name.pl] [params]. Instead try:
p = subprocess.Popen(["C:\\Perl64\\bin\\perl.exe", path+"file_name.pl", "param1", "param2", ...])

Python subprocess.run with stderr=subprocess.PIPE redirects input(text)

I wrote a program (myProg.py) that uses subprocess module to run other python programs through the run function. I noticed that arg in input(arg) statements in these other python programs are not being displayed to the console (stdout), while args in print(args) are displayed properly. This only happens when I run my program through console. This does not happen when I run my program through LiClipse.
Here is the simplest way to replicate this situation:
Using python 3.6.2, and windows 10
create a python program containing the following two lines and save it as someProgram.py:
a = input("Enter anything")
print("a has: " + a)
open cmd, type: python
type: import subprocess
type: subprocess.run(["python", "path..to..someProgram.py"], stderr=subprocess.PIPE)
No ouptut so far but the interpreter is waiting on input... type something and hit Enter.
You will see the output from the print statement.
If you remove , stderr=subprocess.PIPE you will see the correct outputs.
Now, save the code from steps 2 & 3 in another file, call it myProg.py in the same folder as someProgram.py. Run myProg.py from LiClipse. You will find that the myProg.py runs fine and produces the correct outputs.
My questions are:
Why is this problem with subprocess.run happening
How can I solve it
Why would there be a difference between running code through commandline and through an IDE.
input function print prompt text to stderr, this is a known issue
you redirected stderr, therefore prompt text not shown, when you run from LiClipse, stderr not get redirected.
you could output prompt by your self, like:
print("Enter anything", end='')
a = input()
alternatively, import readline module before input, then input will use GNU readline lib (if you have), which prints to stdout. While in your case, the program runs as a subprocess, you could still achieve this:
python -c "import readline; import runpy; runpy.run_path('/path/to/program.py')"

Running an R script from command line (to execute from python)

I'm currently trying to run an R script from the command line (my end goal is to execute it as the last line of a python script). I'm not sure what a batch file is, or how to make my R script 'executable'. Currently it is saved as a .R file. It works when I run it from R.
How do I execute this from the windows command prompt line? Do i need to download something called Rscript.exe? Do I just save my R script as an .exe file? Please advise on the easiest way to achieve this.
R: version 3.3 python: version 3.x os: windows
As mentioned, Rscript.exe the automated executable to run R scripts ships with any R installation (usually located in bin folder) and as #Dirk Eddelbuettel mentions is the recommended automated version. And in Python you can run any external program as a subprocess with various types including a call, check_output, check_call, or Popen and the latter of which provides more facility such as capturing errors in the child process.
If R directory is in your PATH environmental variable, you do not need to include full path to RScript.exe but just name of program, Rscript. And do note this is fairly the same process for Linux or Mac operating systems.
command = 'C:/R-3.3/bin/Rscript.exe' # OR command = 'Rscript'
path2script = 'C:/Path/To/R/Script.R'
arg = '--vanilla'
# CHECK_CALL VERSION
retval = subprocess.check_call([command, arg, path2script], shell=True)
# CALL VERSION
retval = subprocess.call(["'Rscript' 'C:/Path/To/R/Script.R'"])
# POPEN VERSION (W/ CWD AND OUTPUT/ERROR CAPTURE)
curdir = 'C:/Path/To/R/Script'
p = subprocess.Popen(['Rscript', 'Script.R'], cwd=curdir,
stdin = subprocess.PIPE, stdout = subprocess.PIPE,
stderr = subprocess.PIPE)
output, error = p.communicate()
if p.returncode == 0:
print('R OUTPUT:\n {0}'.format(output.decode("utf-8")))
else:
print('R ERROR:\n {0}'.format(error.decode("utf-8")))
You already have Rscript, it came with your version of R. If R.exe, Rgui.exe, ... are in your path, then so is Rscript.exe.
Your call from Python could just be Rscript myFile.R. Rscript is much better than R BATCH CMD ... and other very old and outdated usage patterns.
You probably already have R, since you can already run your script.
All you have to do is find its binaries (the Rscript.exe file).
Then open windows command line ([cmd] + [R] > type in : "cmd" > [enter])
Enter the full path to R.exe, followed by the full path to your script.

Python script not able to read user input when run remotely

I am trying to remotely execute a simple python script userinfo.py present in remotehost.
Below is sourcecode of userinfo.py [ using Python 2.7.10 ]
#############
print "Userinfo :"
name=raw_input("Enter your name")
age=raw_input("Enter your age")
print "Name"+name+"\nAge"+age
#############
But script is working abnormally when run remotely.
[user#localhost]# ssh remotehost python /home/userinfo.py
Userinfo :
Enter your nameEnter your ageName
Age
[user#localhost]#
Execution summary ::
During execution, it doesn't print anything, it directly waits for user input and I just pressed Enter key it will display output as above.
Would like to know why it is not behaving as expected when raw_input is used.
When values are passed as arguments, it works fine.
[user#localhost]# ssh remotehost python userinfo.py xyz 20
Userinfo :
Name xyz
Age 20
[user#localhost]#
below is changed code.
###########
import sys
print "Userinfo :"
name=sys.argv[1]
age=sys.argv[2]
print "Name "+name+"\nAge "+age
############
Would like to know why interactive way is not working as expected and what may be fix.
In a regular terminal, the raw_input prompt is flushed immediately, meaning you will see the prompt "Enter Your Name".
If you run this script through ssh, it saves the output until the script it finished and only then prints everything in the buffer.
What you need is to run python unbuffered, which will force stdout to flush after every output, and thus display to your ssh session. This can be accomplished several ways.
ssh user#remotehost python -u script.py
or make the file executable and unbuffered by adding the following to top of your .py script. Be sure to use your actual python path here:
#! /usr/bin/python - u
and then in make it executable
sudo chmod +x script.py
then
ssh user#remotehost ./script.py

Categories