Python: How to start a process with Administrator Permissions? - python

I am starting the following script from a Windows 7 command line with administrator permissions:
import win32com.client
import time
import SendKeys
import os
from ctypes import *
shell = win32com.client.Dispatch("WScript.Shell")
os.startfile("C:\...exe")
I have also assigned the feature 'Run this programme as an administrator' to python.exe under Properties > Compatibility > Privilege Level. This did not change anything.
The programme still behaves differently when opened this way to how it behaves when I just open it via a double click on screen. Am I missing some important bit here? Will the process invoked in this way not be run as if started with administrator privileges?
Thanks for your help in advance!
Cheers -
Pat

I don't have access to Vista or Windows 7, but you should be able to use the runas command.
import subprocess
subprocess.call(['runas', '/user:Administrator', 'C:/my_program.exe'])

OK ... I figured out what the problem was. It actually had nothing to do with permissions, contrary to my initial suspicion. Sorry about that!
The reason why the application did not work correctly was because the Python script was located and invoked in another directory. For that reason, some of the application's dependencies were not referenced correctly and it couldn't find some of the files it needs to run properly. Moving the python script into the same directory as the invoked application was one way to fix that.
Sorry again for the misleading initial interpretation of what seemed to be the matter.

Related

How to detect if Python is running in Git Bash terminal, or Windows cmd?

I'd like to give my Python scripts the ability to detect whether it was executed in a Git Bash terminal, or the Windows cmd command line interface. For example, I'm trying to write a function to clear the terminal (regardless of which terminal it is), e.g. echoes the clear command if in Git Bash, or cls if in cmd.
I've tried using sys.platform to detect this, but it returns win32 regardless of which type of terminal it was ran in.
Please try using os and psutil modules.
For example,
import os, psutil # Get the parent process name.
pprocName = psutil.Process(os.getppid()).name()
Then you can have your logic depending on the shell.
Additionally, you may want to check https://www.geeksforgeeks.org/clear-screen-python/
I don't believe what you're asking for is possible, but there are several answers here that show all the detections you can do to use the correct type of clear. Usually, it's just best to either make your own window or not clear the screen, sadly.

Python curses Redirection is not supported

I am trying to use Curses in PyDev in Eclipse in Win7.
I have installed Python 3.2 (64bit) and curses-2.2.win-amd64-py3.2. When I input the following testing codes into PyDev:
import curses
myscreen = curses.initscr()
myscreen.border(0)
myscreen.addstr(12, 25, "Python curses in action!")
myscreen.refresh()
myscreen.getch()
curses.endwin()
It did not show any syntax error, so I think the curses was installed correctly.
However, when I ran it as Python Run, the output showed: Redirection is not supported. I do not know where this problem comes from. I googled a lot but can't find related information.
Recent PyCharm versions (I am currently running 2017.2, not sure when this option was added, or if it has been there the entire time) have the option "Emulate terminal in output console". Curses works with this option checked.
You cannot expect to use curses with a non-terminal.
Probably you get this because you are running the script from inside an IDE, like PyCharm or any other.
All IDEs do provide consoles that are not terminals, so that's where the problem comes from.
For a Pycharm user the solution given by codeape works fine :
Snapshot
You can't use any IDE to run python files with the curses package. I used to run in pycharm and naturally couldn't run.
Change to the command line to run:
for testing follow my following steps
on desktop open notepad and copy paste the code and save it as filename.py
open command line change directory to desktop use below command cd Desktop and hit enter type python example.py and hit enter, your program will definitely run
My workaround is to create a Run Configuration that calls a curses script. The little overhead is worth not having to switch to the terminal and manually run the script hundreds of times a session. I use Intellij but I imagine the process should be similar in PyCharm.
The desired result is the convenience of a button to run the script:
First create a script that calls the entry script, for instance:
ptyhon name-of-script.py
Then, to create a configuration for each script:
Go to Edit configuration.
Click the plus button and add a Shell Script.
Enter the path to a shell script.
Here is a picture of a directory with a couple of sample scripts.
I use this process to view my progress. My curses scripts are very modest so fortunately I can live without a debugger.

.pyw launched on startup via registry launches and quits but launching with double click works...?

I have a .pyw script that works when I double click it etc and it stays open till I close it but I've added it to the registry to run at startup. It does run on startup but it doesn't stay open like its set to. It flashes the gui and then just closes.
Any ideas why this is happening or how to fix it?
P.S I don't want to create a shortcut in the startup folder linking to the .pyw file.
I added the my python script to the registry with another python script :p
import _winreg
aReg = _winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE)
aKey = _winreg.OpenKey(aReg, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, _winreg.KEY_WRITE)
_winreg.SetValueEx(aKey,"MyScript",0, _winreg.REG_SZ, myScript_path)
And when I browse that path in the registry:
HKEY_LOCAL_MACHINE > SOFTWARE > Microsoft > Windows > CurrentVersion > Run it is there with the correct path in data and type REG_SZ
There was a very strange error that only happened at startup since one of the processes the script seemed to use hadn't been started yet. Running as a .py with python.exe didn't produce the error, it only happened when the script was run as a .pyw so I wrote the sys.stdout to a file to log its progress and errors.
Before I had used the logging module but it didn't seem to give as much detail as just outputting straight to file.
After checking the file I was able to fix the code so essentially it was a code problem but quite a sneaky one.
My two cents:
had the same issue (.pyw in startup folder just flashed its gui then closed). Added a 'sleep' before the import commands and it worked. I believe the OS takes a little time to get ready for one/some import commands in my code.
#coding:utf-8
from time import sleep
sleep(20)
from Tkinter import *
from Tix import *
from time import strftime
import urllib
from itertools import izip_longest
import winsound

How to install python 3.2.3 on Windows 7 enterprise

although I have been using python a long time very easily in a Linux environment, I have tremendous trouble to even install it correctly in a windows environment. I hope this is a question to be asked here, as it is not directly a programming question.
Especially, I have the following problems:
When on the command line, python is not a recognized command. Do I have to set the Windows path manually myself? If so, how to do that?
When starting a python script, should this be done with python.exe or pythonw.exe? What is the difference?
I also tried to install ipython several times, it never got installed (even after following the starting ipythonenter link description here thread.
When starting a script with python.exe, a window pops up and closes immediately. I saw some hints in putting in a readline command, which is of no help if there is a syntax error in the script. So how to be able to keep the window open, or how to run the command on the cmd.exe?
Thank you for any help on these items.
Alex
1) Look here: www.computerhope.com/issues/ch000549.htm
2) It has already been answered, always try to use search before asking question:
pythonw.exe or python.exe?
4) When using cmd.exe just navigate to your script folder using dir for changing directories and C:,D:,etc. for changing drives. Then run script by typing just the script name. When installed correctly, Python automatically launches .py scripts with python, so you don't have to write 'python' before script name. When run in cmd, window will stay open. If you want it to stay open even when launching script with double-click, use function waiting for user input, see here How to keep a Python script output window open?
You might want to use Python3.3, there is a new launcher for Python scripts in it. By that, you can start Python scripts with py <scriptname> which has the benefit of being installed in your path (C:\Windows\system32) and you can use a shebang to tell whether the script is for Python2 or Python3.
Also
In addition to the launcher, the Windows installer now includes an
option to add the newly installed Python to the system PATH
(contributed by Brian Curtin in issue 3561).

Script works in IDLE, but .py-file doesn't work

I have a tkinter script, which runs just fine in IDLE. However, when I double click the .py-file from Windows Explorer, the console window flashes half a second and then it exits.
I was able to screenprint the console window. It says:
...etc.etc...
NameError: global name 'simpledialog' is not defined
simpledialog is a module in tkinter which I use in my script. As I do from tkinter import *, there is no need to explicitly write tkinter.simpledialog.
It works in IDLE, why not as .py?
IDLE uses Tkinter as its graphical environment. It is possible that your code is relying on a side effect of an import by IDLE itself. This is especially true if you use IDLE without a subprocess.
The simpledialog module does not import when using from tkinter import *.
Try adding this to your code:
import tkinter.simpledialog as simpledialog
Have you updated your PATH environment variable so that your Python executable is found? You can find more information on how to do here - Using Python on Windows
But you basically need to make sure that the folder containing python.exe (e.g. C:\Python32) is displayed when you type the following command from a prompt:
echo %PATH%
I had exactly the same problem with one of my scripts utilizing Tkinter.
Adding call to mainloop() fixed the issue.
See this tutorial for an example: [http://sebsauvage.net/python/gui/#import1
In my case, in the init function I have
def __init__(self,Width=400, Height=400):
# Create GUI window ------------------------------
win = Tk()
...
in the end of init I added:
win.mainloop()
Now it works by just running the file.
Hope this helps
Similar trouble for me just now, in my first week with python. But I dimly remembered a similar problem with a simple early test script and thought the trouble then was # comments.
So I tried that with my Tkinter infused .py script. It ran fine in IDLE as you say, then only flashed when clicked in windows. But there were a couple # commented lines at the top of file.
I took them all out and it now runs no sweat directly in windows. Have a look .. for #.
Sorry, can't seem to delete this post. Now the files work #comments included. Don't know what's up with that. ..
I found that changing the executable py file to a file.pyw fixed the problem. This tells python to execute it using the pythonw.exe which runs the script without the terminal/console in the background.
Not sure why this works, perhaps some screwed up environment variables from a previous python installation.
Changing the file's extension to pyw instead of py might solve the problem

Categories