Reputation: 176
I wrote a program that calls another program from itself through the subprocess
library and then terminates itself through sys.exit()
.
But it's not that simple. There should be a list of questions. (note, it will not be about the script itself, but about the application of this script created through pyinstaller)
APPDATA\Local\test
os.remove(o)
is not executedpath + f'\\{k}.txt'
saves only in APPDATA\Local\test
, and f'{k}test.txt'
only to current folderApparently, the program does not start from appdata at all, but it is not so, because in the task manager it is shown, even twice. What is the reason for this behavior? And how to fix it?
UPD: I have ensured that files are saved only in upadte, writing os.chdir(path)
after else:
. But first execution still cannot complete.
import sys
import os
import time
path = os.path.dirname(os.getenv('APPDATA')) + '\\Local\\test'
try:
os.mkdir(path)
except OSError:
pass
if not os.path.isfile(path + '\\test.exe'):
with open(path + '\\info.txt', 'w', encoding='utf-8') as f:
f.write(sys.argv[0])
subprocess.call(['copy', sys.argv[0], path + '\\test.exe'], shell=True)
subprocess.call(path + '\\test.exe', shell=True)
sys.exit()
else:
with open(path + '\\info.txt', 'r', encoding='utf-8') as f:
o = f.readline()
if os.path.isfile(o):
try:
os.remove(o)
except:
pass
k = 0
while True:
time.sleep(5)
with open(path + f'\\{k}.txt', 'w', encoding='utf-8') as f:
f.write('test message 1')
with open(f'{k}test.txt', 'w', encoding='utf-8') as f:
f.write('test message 2')
k += 1
Upvotes: 3
Views: 247
Reputation: 176
I solved the problem kill the process via taskkill. As a result, the code after else
looks like this:
os.chdir(path)
with open(path + '\\info.txt', 'r', encoding='utf-8') as f:
o = f.readline()
if os.path.isfile(o):
subprocess.call(['TASKKILL', '/IM', 'test.exe', '/F'], shell=True)
os.remove(o)
In doing so, I made the names of the two programs different in order to properly kill the process.
Upvotes: 0
Reputation: 6031
First, you are asking many questions that don't relevant to each other. Second I'm not sure what are you trying to achieve here but I'm going to give you a brief answer for each.
The apps created with PyInstaller (with -F flag) deploys two processes. One for extracting contents of the executable and clean up after the code executed and second of is your program itself. And additionally, you are calling the executable with subprocess
so it would become 4 processes.
After creating your executable, the sys.argv[0]
would be equal to the path of the executable itself. Thus you can't call the os.remove()
to delete the executable itself.
I'm not sure about the question but os.path.dirname(os.getenv('APPDATA'))
would be translated to the user's AppData path, but f'{k}test.txt'
would be translated to the current executable path where executable is located.
Upvotes: 1