Run a powershell script from python that uses Web-Administration module - python

I have a very long powershell script that I need to execute from a python script.
The powershell script works fine when I run it from command line, but fails when I run it from python.
I've simplified my powershell script to the following code, which reproduces the issue.
Powershell Script:
import-module WebAdministration
Add-Type -Path C:\Windows\System32\inetsrv\Microsoft.Web.Administration.dll
Set-WebConfigurationProperty '/system.webServer/proxy' -Name "enabled" -Value "true"
Python Script:
import subprocess
print subprocess.check_output("powershell [pathToMyPowershellScript]");
When I run the powershell script from cmd.exe, it works fine and produces no output.
When I run the python script, it produces the following error:
Set-WebConfigurationProperty : Retrieving the COM class factory for component
with CLSID {688EEEE5-6A7E-422F-B2E1-6AF00DC944A6} failed due to the following
error: 80040154
Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
At [pathToMyPowershellScript]:3 char:1
+ Set-WebConfigurationProperty '/system.webServer/proxy' -Name "enabled" -Value "t ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo
: NotSpecified: (:) [Set-WebConfigurationProperty], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException,
Microsoft.IIs.PowerShell.Provider.SetConfigurationPropertyCommand
I'm running IIS 7.5 on Windows 7 Professional (x64), with Python 2.7 and Powershell 1.0
Any ideas?

I was able to fix this by running the powershell script from the "sysnative" version of cmd:
subprocess.check_call("c:\\windows\\sysnative\\cmd.exe /c
powershell pathToScript", shell=True)
This solves the bitness issue.

Your program may be calling the wrong version of powershell, try explictly calling the exe.
%SystemRoot%\SysWoW64\WindowsPowerShell\v1.0\powershell.exe
Heres some related reading you might find interesting.

Related

how to remove peripheral device from devices and printers in python

I want to remove device specific device attached to my computer when i run a script in python but am not able to do this. Have searched on the web with no solution.
link 1 and
link 2
I learnt i can achieve that with power shell but am not able to achieve that.
This code is able to open the cd rom successfully
import os
os.system('powershell $driveEject = New-Object -comObject Shell.Application; $driveEject.Namespace(17).ParseName("""F:""").InvokeVerb("""Eject""")')
I came across this question how to remove printer from devices and printer which there is no answer for it.
I kindly need assistance achieve such result.
First I prepared a powershell script (s.ps1):
$driveEject = New-Object -comObject Shell.Application
$driveEject.Namespace(17).ParseName("E:").InvokeVerb("Eject")
Then I created a Python script
import os
os.system('powershell.exe -Command ./s.ps1 >log.txt')
After that I got an error in the log file
./s.ps1 : s.ps1 cannot be loaded because
running scripts is disabled on this system. For
more information, see about_Execution_Policies at
http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ ./s.ps1
+ ~~~~~~~
+ CategoryInfo : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess
After reading the article I executed the commands in cmd running under the administrator
> powershell
Windows PowerShell
Copyright (C) 2015 Microsoft Corporation. All rights reserved.
PS > Set-ExecutionPolicy -ExecutionPolicy Unrestricted
After that, I was finally able to run the script. And I saw a pop-up in the tray with a message that I can eject the disk.

Python in vscode

I have downloaded vs code in my windows 10 computer just, I want to learn python in it.
So, I have installed some extensions like "Python" , "Python
for VSCode" ,"code runner".
But when I click on the run button (Ctrl+ALT+N)
I am getting this error in my terminal:
python : The term 'python' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the name,
or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ python -u "e:\C File\Source file\practice.py"
+ ~~~~~~
+ CategoryInfo : ObjectNotFound: (python:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
But when I type py -u "e:\C File\Source file\practice.py"
instead of python -u "e:\C File\Source file\practice.py"
it is working,
Now what should I do to run this at one mouse click, I don't want to run the code by typing the command.
IMHO, most likely your 'Python' global environment variable is not set correctly.
But, since you mention that py -u [File Path] command seems to give you the output I can suggest that you change how "Code Runner" extension sends a Run command.
Steps:
Click File>Preferences>Settings (shortcut Ctrl+,)
Open "settings.json" file (refer to my attached GIF file for reference)
Paste the following code lines at the end of this file ensuring you don't miss any commas (again refer to the attached GIF):
"code-runner.executorMap": {
"python": "py -u",
},
This should change how the Code-Runner extension sends the Run Code command for Python files. Save the settings.json file and try running your code again using the same shortcut Ctrl+Alt+N".
Does this fix your issue, Pranav? If not, maybe post a clipping of the error message again.
Link to the GIF file showing how to insert the code in settings.json file

Powershell not recognizing conda as cmdlet, function, or operable program

I've been having this issue on my new laptop for a couple of hours and cannot figure out what's causing it. I'm trying to install scikit-learn with conda and get the following error
conda : The term 'conda' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ conda install -c anaconda scikit-learn
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (conda:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Has anybody else had a similar issue on Windows 10?
Have you already activated the environment for this use case?
There is a long running thread about this on the GitHub conda discussion regarding conda failures various Windows 7 and higher, here:
https://github.com/conda/conda/issues/626
One suggestion is:
The down and dirty:
Check to see if activate works in cmd.exe.
If doesn't work or not acceptable--as #TurboTim shows:
Powershell needs the path to each env (anaconda3\envs\someenv\py33.exe. Laborious! :p
If you don't mind polluting your powershell a little, you can create a profile script which is run every time you open powershell.
The below will add the functions Invoke-CmdScript, Conda-Activate, Conda-Deactivate to your powershell. See Tim's link above for why.
PS C:> New-Item -Path $profile -ItemType File -Force
This creates a script at:
PS C:\> echo $profile
...something like C:\Users\yourUser\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
Edit that script.
PS C:\> explorer $profile
Add this code, save, and reopen powershell (or . $profile ) :
function Invoke-CmdScript {
param(
[String] $scriptName
)
$cmdLine = """$scriptName"" $args & set"
& $Env:SystemRoot\system32\cmd.exe /c $cmdLine |
Select-String '^([^=]*)=(.*)$' | ForEach-Object {
$varName = $_.Matches[0].Groups[1].Value
$varValue = $_.Matches[0].Groups[2].Value
Set-Item Env:$varName $varValue
}
}
$condaRoot = "$Env:USERPROFILE\Anaconda3"
function Conda-Activate([string]$condaEnv) {Invoke-CmdScript $condaRoot\Scripts\activate.bat $condaEnv}
function Conda-Deactivate {Invoke-CmdScript $condaRoot\Scripts\deactivate.bat}
Usage:
C:\> Conda-Activate TFTheano
C:\> Conda-Activate root
C:\> conda info --envs
Disclaimers: Deactivate, as written, didn't do the job for me, thus I just use Conda-Activate to move around. Also,
I don't suspect there are security cautions with adding Invoke-Cmd to profile, so please chime in if 2 cents
I found this online: Unblock-File -Path .\Get-RemoteProgram.ps1
I'm going to try that command in power shell as soon as I can.
I previously had Python installed before conda and since having both together is said to be bring complications I uninstalled the original Python interpreter. This is what worked for me when the same error came up while trying to run a python script using conda.
TLDR; Simply add the path of conda.exe to the environment variables.

Start python file in Swift

I want to start a pythonscript by pushing a Button in a swift macOS application. I come up with:
let process = Process()
process.launchPath = "/usr/bin/python3"
process.currentDirectoryPath = "\(NSHomeDirectory())" + "/PycharmProjects/untitled5"
process.arguments = ["myscript.py"]
process.launch()
but I get "launch path not accessible" error by executing. If I change launchPath to:
process.launchPath = "/usr/bin/python"
everything works fine, but now I getting python compiling errors because myscript is written in python3.6.0, I have to use python3 because of using a library.
When I open Finder and go to "/usr/bin/python3" it says not found, but python3 is installed, I used it in Pycharm and I'm also able to start python3 in terminal.
In terminal "python3 ~/PycharmProjects/untitled5/myscript.py" works.
On your terminal type
which python3
this will return the path that is accessed when you run python3 from the command line

How to call a shell script from Python in Windows Powershell?

I using a Python script to call a .sh script, as shown below
ret = subprocess.call('sh ./myScript.sh '+file_a+' '+file_b+' '+str(self.counter), shell=True)
The first two lines of myScript.sh are
#!/bin/bash
echo "sh script opened"
I can run myScript.sh directly from Windows Powershell, but not from my Python script(run in Powershell). So, I know that myScript.sh is correct; however, I do not get output when run from my Python script On a different computer, this call worked fine, but now it doesn't. Any suggestions?
As #abarnet mentioned in his comment there is a COMSPEC environement variable that you can change to point at powershell rather than cmd:
import os
import subprocess
print os.environ["COMSPEC"]
os.environ["COMSPEC"] = r"C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe"
print os.environ["COMSPEC"]
ret = subprocess.call('sh ./script.sh', shell=True)
print ret
Which on my Windows machine returns:
C:\Windows\system32\cmd.exe
C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe
The term 'sh' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included , verify that the path is correct and try again. At line:1 char:3
+ sh <<<< ./script.sh
+ CategoryInfo : ObjectNotFound: (sh:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

Categories

Resources