0

I am trying to make a script which would run an .exe file from my computer. I think I am using the wrong command. I tried all the other commands like import os, os.startfile, but they aren't working.

Here is my code:

loop=0
while loop==0:
    answer=raw_input("coded by: Narralol\n\n"
    "Pick a task:\n"
    "1) Start Minecraft.exe\n"
    "2) Start Minecraft_Server.jar\n"
    "3) Backup your server\n"
    "4) Copy the backup to your desktop\n"
    "5) Exit\n")
    if answer==1:
        execfile('D:\Games\Minecraft\Minecraft.exe')
    elif answer==2:
        execfile('D:\Games\Minecraft\Minecraft_server.jar')
    elif answer==5:
        loop=1
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
Narraxus
  • 41
  • 10

2 Answers2

3

Use the subprocess module to run external commands:

import subprocess

    subprocess.call('D:\Games\Minecraft\Minecraft.exe')
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 2
    @JoranBeasley: Even the `os.system` documentation points to `subprocess` as the preferable method; for one, the default argument handling method avoids shell injection vulnerabilities. – Martijn Pieters Sep 21 '12 at 21:35
  • 1
    yeah I know ... but he is controlling the input and doesnt need the output ... so in this case I would say os.system would work fine...but subprocess is certainly the "right" way to do it – Joran Beasley Sep 21 '12 at 21:37
1

You can use os.system() like so (note: it is usually better to use subprocess for doing things like this):

answer = 0
while answer < 5:
    answer = int(raw_input("coded by: Narralol\n\n"
    "Pick a task:\n"
    "1) Start Minecraft.exe\n"
    "2) Start Minecraft_Server.jar\n"
    "3) Backup your server\n"
    "4) Copy the backup to your desktop\n"
    "5) Exit\n").strip())
    if answer == 1:
        os.system('D:\Games\Minecraft\Minecraft.exe')
    elif answer == 2:
        os.system('D:\Games\Minecraft\Minecraft_server.jar')
    elif answer == 5:
        break

Changed a few other minor things in the code like checking an int against another int (instead of string against an int), etc.

chown
  • 51,908
  • 16
  • 134
  • 170
  • Yeah, thank you very much, it's working :) I think the problem was that the answer was recognised as a string rather then an int so it wasn't executing the file. It just kept going in loop without doing anything. Maybe that could be the mistake? – Narraxus Sep 21 '12 at 21:46
  • That is correct, i.e.: `x = "1"; y = 1; x != y; int(x) == y; x == str(y)` – chown Sep 21 '12 at 21:51
  • Oooooh yes I understand now :). That makes perfect sense! – Narraxus Sep 21 '12 at 21:59