I've done some research but I would like to be able to call control-alt-delete from python. If that is not possible is it possible to call it from command line because then I could just use that command in python because I can call command lines in python. If someone could point me in the right direction that would be great. this is for a task manager written with wxPython.
edit:
im trying to launch the windows security and from a user answer i tried
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shell.SendKeys("{CONTROL}{ALT}{DELETE}")
and i get this error
Traceback (most recent call last):
File "C:/Python27/tescontrol.py", line 4, in <module>
shell.SendKeys("{CONTROL}{ALT}{DELETE}")
File "<COMObject WScript.Shell>", line 2, in SendKeys
com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024809), None)
You surely mean activating the Windows Security window. In this case:
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shell.SendKeys("^(%{DELETE})")
UPDATE
The above code seems not to work because of the reasons described in other posts. In that case, the alternative is to create a similar window and call from Python the different programs/functions called by the real Windows Security window.
On reading OP's comments to the original question, OP's final need is to change a user's password. This can be done with:
from win32com import adsi
ads_obj = adsi.ADsGetObject("WinNT://localhost/%s,user" % username)
ads_obj.SetPassword(password)
I just tested this in my PC, so is final information (though not necessarily correct; this is up to the OP :-) ).
UPDATE 2: Copying the later as a separate answer as comments seem to indicate that all of the answer doesn't work. This is correct for the SendKeys proposition, which doesn't work.
If what you want to do is to shutdown or restart the system, Windows has a 'shutdown' command and linux's typically have 'shutdown' and 'reboot' commands.
Check out the following thread:
http://forums.codeguru.com/showthread.php?330557-Ctrl-alt-delete
According to it, VNC uses something like this:
PostMessage HWND_BROADCAST, WM_HOTKEY, 0, MakeLong(MOD_ALT Or MOD_CONTROL, VK_DELETE)
I suspect you would need to use ctypes or PyWin32 to do something like this. I would probably go with ctypes since it's cross-platform, however, even with ctypes you would probably need to write a special method for each OS that you support.
On reading OP's comments, his/her original need was to change the user's password. In fact, this can be done with:
from win32com import adsi
ads_obj = adsi.ADsGetObject("WinNT://localhost/%s,user" % username)
ads_obj.SetPassword(password)
You can use vncdotool library
At:
lib
And use vncdotool by:
os.system("vncdotool key ctrl-alt-del")
Here is one way you can try at least:
(It may only work on windows 7)
import sys
import localize
import os
value_from = 0
Integer = _clear_type_cache(get_object[win\%sys(vnc_value*cache)* value_from])
def Interclass(event):
try:
[<'ctrl'><'alt'><'del'>{%user_value(*object)*value_form}] % cache
except:
{%TOPMOST%'TEMP'_%VALUE_REGISTRY}*
else:
print("No value")
As far as I know, Ctrl-Alt-Delete is protected for security reasons, so programs cannot use it. (At least in Windows 7 and before.)
Related
The program I write should be able to run both directly via the interpreter and via Transcrypt. The problem is that I need to skip some lines when Transcrypt is running and "try" does not work in Transcrypt. Is there any other way to skip lines when running the program via Transcypt? Is it possible to use if ?:
if transctypt is activated:
Thanks in advance!
If there's no built-in method otherwise, you could probably e. g. look for the existence of the document variable. There should be no such thing when not running in the browser. (I haven't tested this.)
try:
assert document
in_transcrypt = True
except Exception:
in_transcrypt = False
Thanks to the fzzylogic's comment I solved the problem like this:
from org.transcrypt.stubs.browser import __pragma__
#__pragma__('skip')
import subprocess
import os
#__pragma__('noskip')
I'm trying to connect another computer in local network via python (subprocesses module) with this commands from CMD.exe
net use \\\\ip\C$ password /user:username
copy D:\file.txt \\ip\C$
Then in python it look like below.
But when i try second command, I get:
"FileNotFoundError: [WinError 2]"
Have you met same problem?
Is there any way to fix it?
import subprocess as sp
code = sp.call(r'net use \\<ip>\C$ <pass> /user:<username>')
print(code)
sp.call(r'copy D:\file.txt \\<ip>\C$')
The issue is that copy is a built-in, not a real command in Windows.
Those Windows messages are awful, but "FileNotFoundError: [WinError 2]" doesn't mean one of source & destination files can't be accessed (if copy failed, you'd get a normal Windows message with explicit file names).
Here, it means that the command could not be accessed.
So you'd need to add shell=True to your subprocess call to gain access to built-ins.
But don't do that (security issues, non-portability), use shutil.copy instead.
Aside, use check_call instead of call for your first command, as if net use fails, the rest will fail too. Better have an early failure.
To sum it up, here's what I would do:
import shutil
import subprocess as sp
sp.check_call(['net','use',r'\\<ip>\C$','password','/user:<username>'])
shutil.copy(r'D:\file.txt,r'\\<ip>\C$')
you need make sure you have right to add a file.
i have testted successfully after i corrected the shared dirctory's right.
Is there a way in Python to detect, within a process, where that process is being executed? I have some code that includes the getpass.getpass() function, which is broken in Spyder, and it's annoying to go back and forth between the command line and the IDE all the time. It would be useful if I could add code like:
if not being run from Spyder:
use getpass
else:
use alternative
Here is the solution I ended up using. After reading Markus's answer, I noticed that Spyder adds half a dozen or so environment variables to os.environ with names like SPYDER_ENCODING, SPYDER_SHELL_ID, etc. Detecting the presence of any of these seems relatively unambiguous, compared to detecting the absence of a variable with as generic a name as 'PYTHONSTARTUP'. The code is simple, and works independently of Spyder's startup script (as far as I can tell):
if any('SPYDER' in name for name in os.environ)
# use alternative
else:
# use getpass
Since the string is at the beginning of each environment variable name, you could also use str.startswith, but it's less flexible, and a little bit slower (I was curious):
>>> import timeit
>>> s = timeit.Timer("[name.startswith('SPYDER') for name in os.environ]", "import os")
>>> i = timeit.Timer("['SPYDER' in name for name in os.environ]", "import os")
>>> s.timeit()
16.18333065883474
>>> i.timeit()
6.156869294143846
The sys.executable method may or may not be useful depending on your installation. I have a couple WinPython installations and a separate Python 2.7 installation, so I was able to check the condition sys.executable.find('WinPy') == -1 to detect a folder name in the path of the executable Spyder uses. Since the warning that shows in IDLE when you try to use getpass is less "loud" than it could be, in my opinion, I ended up also checking the condition sys.executable.find('pythonw.exe') == -1 to make it slightly louder. Using sys.executable only, that method looks like:
if sys.executable.find('pythonw.exe') == sys.executable.find('WinPy') == -1:
# use getpass
else:
# use alternative
But since I want this to work on other machines, and it's much more likely that another user would modify their WinPython installation folder name than that they would rename their IDLE executable, my final code uses sys.executable to detect IDLE and os.environ to detect Spyder, providing a "louder" warning in either case and keeping the code from breaking in the latter.
if any('SPYDER' in name for name in os.environ) \
or 'pythonw.exe' in sys.executable:
password = raw_input('WARNING: PASSWORD WILL BE SHOWN ON SCREEN\n\n' * 3
+ 'Please enter your password: ')
else:
password = getpass.getpass("Please enter your password: ")
By default, Spyder uses a startup scrip, see Preferences -> Console -> Adanced setting. This option is usually set to the scientific_startup.py file that loads pylab et al.
The easiest solution is to just add a global variable to the file and then use that in your if statement, e.g. add this line at the end of scientific_startup.py:
SPYDER_IDE_ACTIVE = True
In your script:
if not 'SPYDER_IDE_ACTIVE' in globals():
use getpass
else:
use alternative
This will work without throwing an error. You can also use exceptions if you like that more.
A second solution would be (if you cannot modify that file for some reason) to just check if the environment variable PYTHONSTARTUP is set. On my machine (using the Anaconda Python stack), it is not set for a regular Python shell. You could do
import os
if not 'PYTHONSTARTUP' in os.environ:
use getpass
else:
use alternative
Spyder provides the option of executing the current editor script in a native system terminal. This would produce identical behavior as if you were running from the command line. To set this up, open the Run Settings dialog by hitting F6. Then select the radio button "Execute in an external System terminal". Now run the script as usual by hitting F5. You should be able to use getpass in the normal fashion with this approach.
You could add env variable when running in Spyder and check it in code.
I'm trying to save myself just a few keystrokes for a command I type fairly regularly in Python.
In my python startup script, I define a function called load which is similar to import, but adds some functionality. It takes a single string:
def load(s):
# Do some stuff
return something
In order to call this function I have to type
>>> load('something')
I would rather be able to simply type:
>>> load something
I am running Python with readline support, so I know there exists some programmability there, but I don't know if this sort of thing is possible using it.
I attempted to get around this by using the InteractivConsole and creating an instance of it in my startup file, like so:
import code, re, traceback
class LoadingInteractiveConsole(code.InteractiveConsole):
def raw_input(self, prompt = ""):
s = raw_input(prompt)
match = re.match('^load\s+(.+)', s)
if match:
module = match.group(1)
try:
load(module)
print "Loaded " + module
except ImportError:
traceback.print_exc()
return ''
else:
return s
console = LoadingInteractiveConsole()
console.interact("")
This works with the caveat that I have to hit Ctrl-D twice to exit the python interpreter: once to get out of my custom console, once to get out of the real one.
Is there a way to do this without writing a custom C program and embedding the interpreter into it?
Edit
Out of channel, I had the suggestion of appending this to the end of my startup file:
import sys
sys.exit()
It works well enough, but I'm still interested in alternative solutions.
You could try ipython - which gives a python shell which does allow many things including automatic parentheses which gives you the function call as you requested.
I think you want the cmd module.
See a tutorial here:
http://wiki.python.org/moin/CmdModule
Hate to answer my own question, but there hasn't been an answer that works for all the versions of Python I use. Aside from the solution I posted in my question edit (which is what I'm now using), here's another:
Edit .bashrc to contain the following lines:
alias python3='python3 ~/py/shellreplace.py'
alias python='python ~/py/shellreplace.py'
alias python27='python27 ~/py/shellreplace.py'
Then simply move all of the LoadingInteractiveConsole code into the file ~/py/shellreplace.py Once the script finishes executing, python will cease executing, and the improved interactive session will be seamless.
Just as the title says. I want to write a script that behaves differently depending on whether it's running inside a console window or in IDLE. Is there an object that exists only when running in IDLE that I can check for? An environment variable?
I'm using Python 2.6.5 and 2.7 on Windows.
Edit:
The answers given so far work. But I'm looking for an official way to do this, or one that doesn't look like a hack. If someone comes up with one, I'll accept that as the answer. Otherwise, in a few days, I'll accept the earliest answer.
I would prefer to do:
import sys
print('Running IDLE' if 'idlelib.run' in sys.modules else 'Out of IDLE')
Google found me this forum post from 2003. With Python 3.1 (for win32) and the version of IDLE it comes with, len(sys.modules) os 47 in the command line but 122 in the IDLE shell.
But why do you need to care anyway? Tkinter code has some annoyances when run with IDLE (since the latter uses tkinter itself), but otherwise I think I'm safe to assume you shouldn't have to care.
I suggest packing all the code in one function (Python 3):
def RunningIntoPythonIDLE():
import idlelib.PyShell
def frames(frame = sys._getframe()):
_frame = frame
while _frame :
yield _frame
_frame = _frame.f_back
return idlelib.PyShell.main.__code__ in [frame.f_code for frame in frames()]
So tkinter apps can do its check:
if not RunningIntoPythonIDLE():
root.mainloop()
I'm a touch late, but since IDLE replaces the standard streams with custom objects (and that is documented), those can be checked to determine whether a script is running in IDLE:
import sys
def in_idle():
try:
return sys.stdin.__module__.startswith('idlelib')
except AttributeError:
return True
My suggestion is to get list of all running frames and check if main Idle method would be in there.
def frames(frame = sys._getframe()):
_frame = frame
while _frame :
yield _frame
_frame = _frame.f_back
import idlelib.PyShell
print(idlelib.PyShell.main.func_code in [frame.f_code for frame in frames()])
the frames function generates frames running at moment of its declaration, so you can check if idle were here.