Self-destroying Python script [duplicate] - python

Is it possible to make a python script that will delete the .py file at the end of its execution (self-delete) in windows?

This way makes your program non OS dependant.
from os import remove
from sys import argv
remove(argv[0])
Bonus points:
When parsing arguments the very first argument that you get in sys.argv is equals to "path-to-filename/filename.py"

Neomind's answer seems to do the trick. But if deleting the file while it's in memory bothers you, and you're looking for a pure python solution, then you could use subprocess to create a new process with the explicit purpose of deleting your original script file. Something like this should work:
import sys, subprocess
subprocess.Popen("python -c \"import os, time; time.sleep(1); os.remove('{}');\"".format(sys.argv[0]))
sys.exit(0)
You probably wouldn't need the timeout in there but I've added it just to make sure that the process from the original script has been given enough time to close itself.

I'm not sure deleting a file while it's in memory would be a good idea. Try running a batch file from the script which closes the script process, then deletes the script file.
There may be a native method to self destruct a script, but I am not aware of it.
EDIT: Here is a simple example of how you could accomplish this using the method I described:
In the script
# C:\test.py
import os
os.startfile(r"C:\sampleBatch.bat")
In the batch
# C:\sampleBatch.bat
TASKKILL /IM "process name" #For me, this was "ipy64.exe" because I use IronPython.
DEL "C:\test.py"
You may not even need to kill the process to delete the file, but it is safer to do so. Hope this helps.

Yes, you could use the following:
import os
import sys
import subprocess
# execute and remove after run
(Your python code)
# end of file
dir = os.getcwd()
os.remove(dir+'\%s' % sys.argv[0])
This script can be modified of course, but besides that this should work

You could also make use of the atexit module.
import os, atexit
atexit.register(lambda file = __file__: os.remove(file))

There is a rather simple method:
import os
os.remove("insert the file's path")
If you're facing problems, place an 'r' before the starting quotations mark.

Related

open and show any file in python [duplicate]

This question already has answers here:
Open document with default OS application in Python, both in Windows and Mac OS
(17 answers)
Closed 8 years ago.
I'm wondering how to open files in programs such as Notepad and Picture Viewer depending on the extension the file has. I'm using Python 3.3 on Windows.
I've done some research and people have mentioned a module named Image, but when I try and import this module I get an ImportError.
Here's what I have so far:
def openFile():
fileName = listbox_1.get(ACTIVE)
if fileName.endswith(".jpg"):
fileName.open()
I will also have HTML and JSON files that I will need to open in Notepad.
On Windows you could use os.startfile() to open a file using default application:
import os
os.startfile(filename)
There is no shutil.open() that would do it cross-platform. The close approximation is webbrowser.open():
import webbrowser
webbrowser.open(filename)
that might use automatically open command on OS X, os.startfile() on Windows, xdg-open or similar on Linux.
If you want to run a specific application then you could use subprocess module e.g., Popen() allows to start a program without waiting for it to complete:
import subprocess
p = subprocess.Popen(["notepad.exe", fileName])
# ... do other things while notepad is running
returncode = p.wait() # wait for notepad to exit
There are many ways to use the subprocess module to run programs e.g., subprocess.check_call(command) blocks until the command finishes and raises an exception if the command finishes with a nonzero exit code.
Use this to open any file with the default program:
import os
def openFile():
fileName = listbox_1.get(ACTIVE)
os.system("start " + fileName)
If you really want to use a certain program, such as notepad, you can do it like this:
import os
def openFile():
fileName = listbox_1.get(ACTIVE)
os.system("notepad.exe " + fileName)
Also if you need some if checks before opening the file, feel free to add them. This only shows you how to open the file.
Expanding on FatalError's suggestion with an example.
One additional benefit of using subprocessing rather than os.system is that it uses the same syntax cross-platform (os.system on Windows requires a "start" at the beginning, whereas OS X requires an "open". Not a huge deal, but one less thing to remember).
Opening a file with subprocess.call.
All you need to do to launch a program is call subprocess.call() and pass in a list of arguments where the first is the path to the program, and the rest are additional arguments that you want to supply to the program you're launching.
For instance, to launch Notepad.exe
import subprocess
path_to_notepad = 'C:\\Windows\\System32\\notepad.exe'
path_to_file = 'C:\\Users\\Desktop\\hello.txt'
subprocess.call([path_to_notepad, path_to_file])
Passing multiple arguments and paths is equally as simple. Just add additional items to the list.
Launching with multiple arguments
This, for example, launches a JAR file using a specific copy of the Java runtime environment.
import subprocess
import os
current_path = os.getcwd()
subprocess.call([current_path + '/contents/home/bin/java', # Param 1
'-jar', #Param2
current_path + '/Whoo.jar']) #param3
Argument 1 targets the program I want to launch. Argument2 supplies an argument to that program telling it that it's going to run a JAR, and finally Argument3 tells the target program where to find the file to open.

How to run a .py file from a .py file in an entirely different project

For the life of me i can't figure this one out.
I have 2 applications build in python, so 2 projects in different folders, is there a command to say in the first application like run file2 from documents/project2/test2.py ?
i tried something like os.system('') and exec() but that only seems to work if its in the same folder. How can i give a command a path like documents/project2 and then for example:
exec(documents/project2 python test2.py) ?
short version:
Is there a command that runs python test2.py while that test2 is in a completely different file/project?
thnx for all feedback!
There's a number of approaches to take.
1 - Import the .py
If the path to the other Python script can be made relative to your project, you can simply import the .py. This will cause all the code at the 'root' level of the script to be executed and makes functions as well as type and variable definitions available to the script importing it.
Of course, this only works if you control how and where everything is installed. It's the most preferable solution, but only works in limited situations.
import ..other_package.myscript
2 - Evaluate the code
You can load the contents of the Python file like any other text file and execute the contents. This is considered more of a security risk, but given the interpreted nature of Python in normal use not that much worse than an import under normal circumstances.
Here's how:
with open('/path/to/myscript.py', 'r') as f:
exec(f.read())
Note that, if you need to pass values to code inside the script, or out of it, you probably want to use files in this case.
I'd consider this the least preferable solution, due to it being a bit inflexible and not very secure, but it's definitely very easy to set up.
3 - Call it like any other external program
From a Python script, you can call any other executable, that includes Python itself with another script.
Here's how:
from subprocess import run
run('python path/to/myscript.py')
This is generally the preferable way to go about it. You can use the command line to interface with the script, and capture the output.
You can also pipe in text with stdin= or capture the output from the script with stdout=, using subprocess.Popen directly.
For example, take this script, called quote.py
import sys
text = sys.stdin.read()
print(f'In the words of the poet:\n"{text}"')
This takes any text from standard in and prints them with some extra text, to standard out like any Python script. You could call it like this:
dir | python quote.py
To use it from another Python script:
from subprocess import Popen, PIPE
s_in = b'something to say\nright here\non three lines'
p = Popen(['python', 'quote.py'], stdin=PIPE, stdout=PIPE)
s_out, _ = p.communicate(s_in)
print('Here is what the script produced:\n\n', s_out.decode())
Try this:
exec(open("FilePath").read())
It should work if you got the file path correct.
Mac example:
exec(open("/Users/saudalfaris/Desktop/Test.py").read())
Windows example:
exec(open("C:\Projects\Python\Test.py").read())

How to run this function in a seperate process on Windows?

I am trying to run this code in the background (from command line) on Windows using python 2.7:
import httpimport
mod = httpimport.load('module name','URL')
Everything works, but the process lingers when launched and only ctrl + c will end it. I am looking to start an independent process from this in the background.
I have read that multiprocess can come useful here but I would need some pointers if I may.
Any suggestions ?
EDIT: I may add this is a script which is calling another python script from URL. From the answers below I gathered that I might need to change my remote script first.
if you want to run your process in the background you can use spawnl
import os
os.spawnl(os.P_DETACH, 'python code.py "module name" "url"')
but you need to be cautious, you can't kill the process if you don't knew it's pid or check where it is running via task manager
check for more: https://docs.python.org/2/library/os.html#os.spawnl
for your code (for exemple code.py):
import httpimport
from sys import argv
name, module_name, URL = argv # here you get the module name and URL from the argument given from before
mod = httpimport.load(module_name , URL)

How to make scripts auto-delete at the end of execution?

Is it possible to make a python script that will delete the .py file at the end of its execution (self-delete) in windows?
This way makes your program non OS dependant.
from os import remove
from sys import argv
remove(argv[0])
Bonus points:
When parsing arguments the very first argument that you get in sys.argv is equals to "path-to-filename/filename.py"
Neomind's answer seems to do the trick. But if deleting the file while it's in memory bothers you, and you're looking for a pure python solution, then you could use subprocess to create a new process with the explicit purpose of deleting your original script file. Something like this should work:
import sys, subprocess
subprocess.Popen("python -c \"import os, time; time.sleep(1); os.remove('{}');\"".format(sys.argv[0]))
sys.exit(0)
You probably wouldn't need the timeout in there but I've added it just to make sure that the process from the original script has been given enough time to close itself.
I'm not sure deleting a file while it's in memory would be a good idea. Try running a batch file from the script which closes the script process, then deletes the script file.
There may be a native method to self destruct a script, but I am not aware of it.
EDIT: Here is a simple example of how you could accomplish this using the method I described:
In the script
# C:\test.py
import os
os.startfile(r"C:\sampleBatch.bat")
In the batch
# C:\sampleBatch.bat
TASKKILL /IM "process name" #For me, this was "ipy64.exe" because I use IronPython.
DEL "C:\test.py"
You may not even need to kill the process to delete the file, but it is safer to do so. Hope this helps.
Yes, you could use the following:
import os
import sys
import subprocess
# execute and remove after run
(Your python code)
# end of file
dir = os.getcwd()
os.remove(dir+'\%s' % sys.argv[0])
This script can be modified of course, but besides that this should work
You could also make use of the atexit module.
import os, atexit
atexit.register(lambda file = __file__: os.remove(file))
There is a rather simple method:
import os
os.remove("insert the file's path")
If you're facing problems, place an 'r' before the starting quotations mark.

Running an outside program (executable) in Python?

I just started working on Python, and I have been trying to run an outside executable from Python.
I have an executable for a program written in Fortran. Let’s say the name for the executable is flow.exe. And my executable is located in C:\Documents and Settings\flow_model. I tried both os.system and popen commands, but so far I couldn't make it work. The following code seems like it opens the command window, but it wouldn't execute the model.
# Import system modules
import sys, string, os, arcgisscripting
os.system("C:/Documents and Settings/flow_model/flow.exe")
How can I fix this?
If using Python 2.7 or higher (especially prior to Python 3.5) you can use the following:
import subprocess
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
Runs the command described by args. Waits for command to complete, then returns the returncode attribute.
subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
Runs command with arguments. Waits for command to complete. If the return code was zero then returns, otherwise raises CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute
Example: subprocess.check_call([r"C:\pathToYourProgram\yourProgram.exe", "your", "arguments", "comma", "separated"])
In regular Python strings, the \U character combination signals a
extended Unicode code point escape.
Here is the link to the documentation: http://docs.python.org/3.2/library/subprocess.html
For Python 3.5+ you can now use run() in many cases: https://docs.python.org/3.5/library/subprocess.html#subprocess.run
Those whitespaces can really be a bother. Try os.chdir('C:/Documents\ and\ Settings/') followed by relative paths for os.system, subprocess methods, or whatever...
If best-effort attempts to bypass the whitespaces-in-path hurdle keep failing, then my next best suggestion is to avoid having blanks in your crucial paths. Couldn't you make a blanks-less directory, copy the crucial .exe file there, and try that? Are those havoc-wrecking space absolutely essential to your well-being...?
The simplest way is:
import os
os.startfile("C:\Documents and Settings\flow_model\flow.exe")
It works; I tried it.
I'd try inserting an 'r' in front of your path if I were you, to indicate that it's a raw string - and then you won't have to use forward slashes. For example:
os.system(r"C:\Documents and Settings\flow_model\flow.exe")
Your usage is correct. I bet that your external program, flow.exe, needs to be executed in its directory, because it accesses some external files stored there.
So you might try:
import sys, string, os, arcgisscripting
os.chdir('c:\\documents and settings\\flow_model')
os.system('"C:\\Documents and Settings\\flow_model\\flow.exe"')
(Beware of the double quotes inside the single quotes...)
Use subprocess, it is a smaller module so it runs the .exe quicker.
import subprocess
subprocess.Popen([r"U:\Year 8\kerbal space program\KSP.exe"])
By using os.system:
import os
os.system(r'"C:/Documents and Settings/flow_model/flow.exe"')
Try
import subprocess
subprocess.call(["C:/Documents and Settings/flow_model/flow.exe"])
If it were me, I'd put the EXE file in the root directory (C:) and see if it works like that. If so, it's probably the (already mentioned) spaces in the directory name. If not, it may be some environment variables.
Also, try to check you stderr (using an earlier answer by int3):
import subprocess
process = subprocess.Popen(["C:/Documents and Settings/flow_model/flow.exe"], \
stderr = subprocess.PIPE)
if process.stderr:
print process.stderr.readlines()
The code might not be entirely correct as I usually don't use Popen or Windows, but should give the idea. It might well be that the error message is on the error stream.
in python 2.6 use string enclosed inside quotation " and apostrophe ' marks. Also a change single / to double //.
Your working example will look like this:
import os
os.system("'C://Documents and Settings//flow_model//flow.exe'")
Also You can use any parameters if Your program ingest them.
os.system('C://"Program Files (x86)"//Maxima-gcl-5.37.3//gnuplot//bin//gnuplot -e "plot [-10:10] sin(x),atan(x),cos(atan(x)); pause mouse"')
finally You can use string variable, as an example is plotting using gnuplot directly from python:
this_program='C://"Program Files (x86)"//Maxima-gcl-5.37.3//gnuplot//bin//gnuplot'
this_par='-e "set polar; plot [-2*pi:2*pi] [-3:3] [-3:3] t*sin(t); pause -1"'
os.system(this_program+" "+this_par)
import os
path = "C:/Documents and Settings/flow_model/"
os.chdir(path)
os.system("flow.exe")
Note added by barlop
A commenter asked why this works. Here is why.
The OP's problem is os.system("...") doesn't work properly when there is a space in the path. (Note os.system can work with ('"...."') but anyhow)
Had the OP tried their program from a cmd prompt they'd have seen the error clearly.
C:\carp>type blah.py
import os
os.system(R"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe")
C:\carp>python blah.py
'C:\Program' is not recognized as an internal or external command,
operable program or batch file.
C:\carp>
So it's fine for os.system("calc.exe") (there calc.exe is in the path environment variable). Or for os.system(R"c:\windows\system32\calc.exe"). There's no space in that path.
C:\>md "aa bb cc"
C:\>copy c:\windows\system32\calc.exe "c:\aa bb cc\cccalc.exe"
1 file(s) copied.
This works (Given file "c:\aa bb cc\cccalc.exe" )
import os
os.chdir(R"c:\aa bb cc")
os.system("cccalc.exe")
Other options are subprocess.run and subprocess.popen.
Is that trying to execute C:\Documents with arguments of "and", "Settings/flow_model/flow.exe"?
Also, you might consider subprocess.call().
There are loads of different solutions, and the results will strongly depend on:
the OS you are using: Windows, Cygwin, Linux, MacOS
the python version you are using: Python2 or Python3x
As I have discovered some things that are claimed to work only in Windows, doesn't, probably because I happen to use Cygwin which is outsmarting the OS way to deal with Windows paths. Other things only work in pure *nix based OS's or in Python2 or 3.
Here are my findings:
Generally speaking, os.system() is the most forgiving method.
os.startfile() is the least forgiving. (Windows only && if you're lucky)
subprocess.Popen([...]) not recommended
subprocess.run(winView, shell=True) the recommended way!
Remembering that using subprocess for anything may pose a security risk.
Try these:
import os, subprocess
...
winView = '/cygdrive/c/Windows/explorer.exe %s' % somefile
...
# chose one of these:
os.system(winView)
subprocess.Popen(['/cygdrive/c/Windows/explorer.exe', 'somefile.png'])
subprocess.run(winView, shell=True)
Q: Why would you want to use explorer in Windows?
A: Because if you just want to look at the results of some new file, explorer will automatically open the file with whatever default windows program you have set for that file type. So no need to re-specify the default program to use.
That's the correct usage, but perhaps the spaces in the path name are messing things up for some reason.
You may want to run the program under cmd.exe as well so you can see any output from flow.exe that might be indicating an error.
for the above question this solution works.
just change the path to where your executable file is located.
import sys, string, os
os.chdir('C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\\bin64')
os.system("C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\bin64\\flowwork.exe")
'''import sys, string, os
os.chdir('C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\\bin64')
os.system(r"C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\bin64\\pdftopng.exe test1.pdf rootimage")'''
Here test1.pdf rootimage is for my code .

Categories