How to run Python script from R? - python

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.

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

trouble creating virtual environment for python 3 in windows 10

I want to create a virtualenv in Windows 10 for python 3.7
I'm trying to follow the instruction from python doc
So first I entered the command
PS T:\python -m venv c:\path\to\myenv
it did create directories and files into that path
then according to the documentation, using PowerShell I entered:
PS T:\path\to\myenv\Scripts\Activate.ps1
but I got the following:
The term
'T:\path\to\myenv\Scripts\Activate.ps1' 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
+ T:\path\to\myenv\Scripts\Activate.ps1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (T:\path\to\myenv...ts\Activate.ps1:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
What am I missing
you should replace
path\to\myenv
to your actual path
so as said in docs
C:\> <venv>\Scripts\Activate.ps1
for example it should be something like
C:\>MyProjectsFolder\first_project\venv\Scripts\Activate.ps1
the other workaround is to manually change directories to Scripts folder and then run
Activate.ps1
if it didnt solve your problem please specify your project folder and structure

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

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