0

i created a script that creating a schedueld task from command line on task manager, the problem is that some proccess are launched without a full path on the command line from task manager, i managed to find the location for the process with this line:

location = psutil.Process(pid=int(pid)).exe()

but the problem is that some commands are printed with the location like this:

C:\Users\jacob\AppData\Local\slack\app-4.3.4\slack.exe --type=gpu-process

and some of them like this:

slack.exe --type=gpu-process

how can i strip the file path from every command and add it from the location variable from this script:

import psutil
import os
os.system("""powershell -command ""Unregister-ScheduledTask -TaskPath "\Lsports Tasks\" -a""")
commands = []
for proc in psutil.process_iter(['pid','name']):
  process = proc.info 
  if process['name'] == 'slack.exe':
     pid = process['pid']
     cmds = psutil.Process(pid=int(pid)).cmdline()
     cmda = ' '.join(cmds)
     cmd=os.path.split(cmda)
     print(cmd)


     commands.append(cmd)
     location = psutil.Process(pid=int(pid)).exe()
     print(location)

 i = 0
 for c in commands:
  i+= 1
  task = os.system(f"""SCHTASKS /CREATE /SC ONSTART /RU system /TN "Lsports Tasks\Lsports Runner{i}" /TR "{c}""".format(i,c=c))
Jacob Amar
  • 61
  • 4

1 Answers1

0

To answer your specific question:

how can i strip the file path from every command and add it from the location variable from this script

cmdline() returns the command line the process was called with as a list of strings. The first item is almost always the filepath of the executable. As you've pointed out, sometimes it only has the filename, and not the absolute filepath of the executable. You should replace the first item with the result of exe(), which returns the absolute filepath of the process executable.

for proc in psutil.process_iter():
    if proc.name() == "slack.exe":
        command = proc.cmdline()
        command[0] = proc.exe()

You might experience problems with os.system if there are spaces in the command or command's arguments. At least use subprocess.Popen so you can pass it command as a list, without having to muck around with ' '.join(command) and worrying about spaces double quotes.

I would create the scheduled task as per the answer in this question: Is there a way to add a task to the windows task scheduler via python 3?

GordonAitchJay
  • 4,640
  • 1
  • 14
  • 16