Using Python script to run a full independent powershell script - python

I am a noob, self-motivated programmer, and had been researching methods to use my Python script to run a Powershell file that will copy and image and place the image into Excel.
I've used the subprocess, call, and Popen commands in an attempt to call and run the Powershell program from the Python script, but none has worked.
Some of the examples I found only called different functions of a Powershell script, but when I tried those settings it didn't work for my program. All of the setup for my Powershell has been established so that it can run with my PC, and also runs well when launched independently from Python.
What I would like to ask is if I had, for example, a My_program.py file and a Moving_image.ps1 file. I want to use my .py file to run/execute my .ps1 file, while both programs are located in the same path (C:\Users\Scripts).
What line of code(s), imports, and other program setup's would I need in my Python file to simply run the independent .ps1 file from my Python script?
I don't need the Powershell script to return anything to the Python script. I would like for it to simply run the copy and paste the command I sent it.
Thank you. Any type of guidance that will lead to this program actually functioning properly will be most appreciated!

Here's what worked for me (testing on linux):
python script test.py
from subprocess import call
call(["/opt/microsoft/powershell/6.0.4/pwsh", "./test.ps1"])
powershell script test.ps1
Import-Module '/home/veefu/pwshmodules/testMod'
Write-Output "Hello from test.ps1"
Get-HelloWorld
testMod.psm1 module, stored at /home/veefu/pwshmodules/testMod
function Get-HelloWorld {
Write-Output "Hello World (from Module)"
}
result when running the python script:
Hello from test.ps1
Hello World (from Module)
On windows you'll probably have to provide the complete path, C:\Windows\system32\MicrosoftPowerShell\1.0\powershell.exe and you may have to pass /file .\yourOtherScript.ps1 in the second argument to call

Related

How do force or change my terminal to run python executable file in python 3 just by opening the file?

My terminal is running python 2 so when I run my python file the program fails.
So basically I am new to programming and trying to create a small python script to help me auto create folders. I also want to give the script to colleges so that they can use it on their systems too.
I know that I can run my file in terminal by using "python3 myfile.py" and it will work, but that's too much off a mission to do for my colleges and as my colleges are not familiar with code or terminal for that matter, I wanted to create an executable file so that they just click to open type a few answers to the promoted question and boom folders created.
This is where I run into a problem, I have "#!/usr/bin/env python3" at the top of my file but when I run the script IDLE opens up and it just shows the code I have written but doesn't seem to run the actual script I wrote. Am I doing something wrong?
I also then though perhaps I could just use the terminal to run the file as it is now executable, so I go into terminal and enter "myfile.py" and the program runs but in python 2 so my script fails as it is in python3. So another question would be is there a way to code into my python file, when running this file make sure you use python3? as I would want this to work on all colleges system without them having to write out anything in terminal?
Sorry for the long explanation but any advice would be greatly appreciated.
Thank you in advance
When you are on windows you can just create a .bat file where you write: python3 myfile.py in it.
Both files have to be in the same directory.
If you want to have a .exe you can also use py2exe.
You could also try just #!/usr/bin/python3 without env.
More here.

How to open .py script within python session in PowerShell (newbie)?

I am new to python and try some simple codes using PowerShell.
I can start python by just typing py and then do codes line for line.
PS C:\Users\...\python> py
[Python starts]
>>> [I can type my code. everything is fine.]
When I try a bit more 'complex' code it is easier to write it in a .py file and run it from PowerShell, which also works fine. However, only when python is not running, i.e., I am simply within my home directory.
PS C:\Users\...\python> py game1.py
[desired output]
PS C:\Users\...\python>
The script runs fine and I get all the output, but I don't know how
to access values, classes, functions, output, etc. from the session.
Now here is my really stupid question: Can I run a .py file within a Python session in PowerShell?
Many thanks in advance!

Python: Subprocess "call" function can't find path

I have a python program that needs to run a bash command on a server. The program works when I run a bash command in my local directory like this:
import subprocess
from subprocess import call
call(['bash', 'Script_Test.sh'])
However, after SSH'ing to a server and running a similar line of code below with a path on the server to a bash script, I get the error "No such file or directory"
call['bash', path]
This doesn't make sense for a number of reasons. I triple checked that the path is correct. I went on Putty, connected to the server on there, and ran a bash command with the same path and it worked, so it can't be the path. I also ran a number of tests to make sure I was SSH'd into the correct server, and I was. I thought there was a security issue on the server with me running bash, so I tried cat instead. Nope, still unable to locate the path.
I'm not super familiar with python subprocesses, so any pointers to anything I'm missing here with "call" would be very helpful.
Making Sure Your Script is Ready for Execution
Give your script a shebang line
First things first, it is important that you include a shebang line in your script on Unix-like systems. I recommend, for your script's portability, that you use #!/usr/bin/env bash.
A Note on File Extensions:
I would recommend that you remove the .sh extension from your script. If you are using the Bourne Again Shell (bash) to execute your script, then using the .sh extension is misleading. Simply put, the Bourne Shell (sh) is different than the Bourne Again Shell (bash) - so don't use a file extension that suggests you are using a different shell than you actually are!
It's not the end of the world if you don't do change your file extension - your script will still be executed as a bash script if you have the proper bash shebang line. Still, it is good practice to either use no file extension (Script_Test -- strongly preferred) or the .bash file extension (Script_Test.bash).
Give your script the proper file permissions
For your purposes, maybe it is only important to give the current user permissions to read and execute the script. In that case, use chmod u+x Script_Test.sh. What is important here is that the correct user (u+) / group (g+) has permissions to execute the script.
Make sure that your script's path is in the $PATH environment variable
Executing your bash script in a Python script
Once you've followed these steps, your Python script should work as you've called it in your question:
import subprocess
from subprocess import call
your_call = call("Test_Script.sh")
If you would rather not move your script into the $PATH environment variable, just make sure that you refer to the script's full path (which is the current directory, ./, in your case):
import subprocess
from subprocess import call
your_call = call("./Test_Script.sh")
Lastly, if your script does not have a shebang line, you will need to specify an additional parameter in your call function:
import subprocess
from subprocess import call
your_call = call("./Test_Script.sh", shell=True)
However, I would not recommend this last approach. See the Python 2.7.12 documentation for the subprocess package...
Warning: Using shell=True can be a security hazard. See the warning under Frequently Used Arguments for details.
Please check out #zenpoy's explanation to a similar StackOverflow question if you are still having problems.
Happy coding!

Unable to run .py file from putty, Syntax error: word unexpected (expecting ")")

I am new to both Python and Linux and as such request simple explanations with minimal assumed knowledge where possible please, however I am more than willing to invest time and effort to learn.
I have a Raspberry Pi 2 (Model B V1.1) that is running Linux. I interact with this pi via putty.
I am trying to create a simple competitive reflex game, consisting of 2 buttons and a single LED. My goal is to have the LED light up after a short interval, and the first player to press their button wins.
I am writing the script for this with python (specifically 2.7.3)
My issue is that i am unable to run ANY .py file from within putty, i always receive the same error:
Syntax error: word unexpected (expecting ")")
To determine if the issue was an error in my code, i created a very very simple .py file, to check if the same error occurs, and it did. So i currently believe even if my code was functional, something is stopping me from running ANY .py file.
The process I am using is as follows:
First I create a new python file from within putty:
sudo nano test.py
Next I enter my python code (very simple for now, as i cannot get ANY .py file to run)
for each in range(5):
print 'hello'
I then press CTRL + O to write the file, hit enter, then CTRL + X to exit
Finally, I make the file executable using
sudo chmod u+x test.py
and try to run it
sudo ./test.py
again, a similar error occurs
Syntax error: "(" unexpected
I then decided to enter the code directly into the python shell, using
sudo python
>>>for each in range(5):
... print 'hello'
This time the output is the desired outcome:
hello
hello
hello
hello
hello
So there is no problem in executing python code directly from the shell, I am just unable to execute any previously saved .py file
Any insight into what could be causing this is much appreciated, and I apologise if I have not provided enough information to be useful for you.
Thanks in advance!
Short answer: Either run these as python filename.py, or else add the line #!/usr/bin/python to the top of your Python scripts.
Long answer: When you run a file from the command line in Linux (which is what the Raspberry Pi is running), by default it assumes that the file is a shell script file (usually Bash script). So it uses the Bash shell (or some other shell, but it's usually Bash) to interpret the file, and Bash doesn't know Python syntax. If you want to run your file using a different interpreter (Python, in this case), you have to add a "magic line" at the top of the file starting with #! (usually pronounced "hash-bang", and sometimes pronounced "shebang" for short). Following the #! characters is the full path of the interpreter to use, e.g. /usr/bin/python for Python scripts. (You can also use /usr/bin/env python as another answer suggested; I prefer /usr/bin/python because it's impossible to get the wrong Python interpreter that way. But that's getting into advanced topics that may be more than you need right now.)
So when you put the line #!/usr/bin/python at the top of your Python scripts, you're telling the Linux system which interpreter to run the program with, and then it should All Just Work™.
Also, STOP using sudo to edit and run these! That's just asking for trouble.
If you wish to execute like this you need the following line as the first line
#!/usr/bin/env python
This will tell bash (or equivalent) to execute the file with the Python interpreter.
If you don't want to do that then you can execute the script like this:
$ python test.py
If you go this route then you don't need to grant execute permissions on the script itself.
Also, scripts shouldn't be executed with sudo unless absolutely necessary.

Run a program in Python's subprocess module, with required files from Terminal

Is it feasible to run a program in Python's subprocess module, but with files from Terminal?
So I want to run the following program from within Python:
myProgram -a myArg
However, suppose that the above program requires the file myFile in the current directory, and it doesn't take the required file as an argument. So, if you run the above program in the directory where there is myFile, the program succeeds in processing. However, if you run it in the directory where there is NOT myFile, the execution fails.
And when I tried to execute the program from within Python's subprocess.Popen(), with shell=True, the program doesn't work and it looks like the reason it failed is the program wasn't able to read myFile when executed from within Python.
So, is there any way to run it successfully from within Python?
subprocess.Popen('myProgram -a myArg', cwd='/folder/with_myFile/')
Similar Question: Python specify popen working directory via argument

Categories

Resources