how to remove peripheral device from devices and printers in python - 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.

Related

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

How to run Python script from R?

I'm trying a simple example but it fails:
system("cmd.exe", input = 'python --version')
Microsoft Windows [Wersja 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. Wszelkie prawa zastrzezone.
C:\Users\cp\Documents\R DATA\LocalAuth>python --version
Nazwa 'python' nie jest rozpoznawana jako polecenie wewnetrzne lub zewnetrzne,
program wykonywalny lub plik wsadowy.
I understand, the cmd should not work there, but when I open:
system("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", input = 'python --version')
Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.
PS C:\Users\cp\Documents\R DATA\LocalAuth> python --version
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 --version
+ ~~~~~~
+ CategoryInfo : ObjectNotFound: (python:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
When I open this console manually it works, but, in properties I see the full path:
%windir%\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy ByPass -NoExit -Command "& 'C:\ProgramData\Anaconda3\shell\condabin\conda-hook.ps1' ; conda activate 'C:\ProgramData\Anaconda3' "
How can I use it with all these parameters in R? When I try to use it link within system command I get:
Error in "%windir%\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy ByPass -NoExit -Command " & :
operations are possible only for numeric, logical or complex types
I guess this must work someway: while I enter the dir within command console (cmd.exe) to "C:\ProgramData\Anaconda3" and type python --version I get a message but with
system("C:\\ProgramData\\Anaconda3\\ python --version") it doesn't work. Why?
EDIT
Found non-elegent solution
setwd("C:/ProgramData/Anaconda3/")
system(command = 'cmd.exe', input = 'python --version')
It works but changes the working dir which is not required.

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.

Pywinrm and Active Directory PowerShell cmdlets

I encounter a weird issue with my Python code which uses pywinrm module.
Let me explain a bit. I have a Linux server where I launch the following python script:
import winrm
"""Create security group"""
s = winrm.Session('https://servername:5986/wsman',
auth=(None, None), transport='kerberos',
server_cert_validation='ignore')
name = "test"
path = "OU=Security Groups,DC=test,DC=org"
ps_command = 'New-ADGroup -Name "{0}"
-GroupScope Universal
-GroupCategory Security
-Path "{1}" -Server ldap.test.org'.format(name, path)
r = s.run_ps(ps_command)
if r.status_code == 0 :
print(r.std_out.decode('UTF-8'))
else:
print(r.std_err('UTF-8'))
This one will connect on the HTTPS listener of a Windows server (not a DC) which then will launch the command of the group creation.
When I launch the AD cmdlet directly on the Windows server, it works perfectly and the security group is created within the AD. But via the script, I have the following response:
$ python3 test_winrm.py
New-ADGroup : Unable to contact the server. This may be because this server does not exist, it is currently down,
or it does not have the Active Directory Web Services running.
At line:1 char:1
+ New-ADGroup -Name "test" -GroupScope Universal -GroupCategory Security
-Path "O ...
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
+ CategoryInfo : ResourceUnavailable: (:) [New-ADGroup], ADServer
DownException
+ FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirector
y.Management.Commands.NewADGroup
I want also to notice that if I replace the current PowerShell command by a basic one (for instance, creation of a folder on the Windows server), it works.
So it works on the Windows server locally but not with AD cmdlets even if RSAT is installed... Have you previous experience on this topic?
Thanks for the help.
Thanks a lot #BenH for your help, you had right on the source of my issue and after several days/headaches, I finally found the solution here: https://github.com/diyan/pywinrm/issues/58.
When using kerberos and pywinrm, you have to set kerberos_delegation=True for multi-hop support.

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

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.

Categories

Resources