0

I have a basic game up and running and I am part way through writing the code for the main menu section for the game which is launched to welcome the user.

I was wondering if it would be possible to launch the main game once the user selects the "Start game" section of the menu. Currently I have two different .py files, one for my game menu and one for the game itself, is there a specific way I can get the menu.py to run the game.py once the "Start game" option is selected?

nobody
  • 19,814
  • 17
  • 56
  • 77
Oscar
  • 97
  • 4
  • 14
  • 2
    You can `import` from other modules you write just as you can from the standard library: see [the docs](https://docs.python.org/2/tutorial/modules.html). – jonrsharpe May 02 '14 at 13:38
  • @jonrsharpe Thanks for your reply, I tried importing the external py document however I was met with an error stating "No module named game". Am I doing something wrong? :( – Oscar May 02 '14 at 13:46
  • 1
    Try reading [this question](http://stackoverflow.com/questions/2325923/how-to-fix-importerror-no-module-named-error-in-python) and generally searching for that error. – jonrsharpe May 02 '14 at 13:55

1 Answers1

0

First of all, you won't be able to import it unless:

A: both programs are in the same directory, or B: the program you are trying to import is in a directory that is part of the PYTHONPATH variable.

However, either way, this is not the best way to run an external py file. It sounds like you want it to run ideally as an independent program, not as part of your current one. A program you import really shouldn't run anything upon importing, but should really just define some functions and variables for the main program's use. What you should use to run the program instead is subprocess, which launches a new program as if you had typed it into the command line.

Here is an example of code to run an external file. The other advantage of this way method is that the file does not have to be in the programs current working directory, it just has to have the file path of the program. Here is an example of the code:

import subprocess
filepath = "Documents/game"
subprocess.call("python "+filepath)

This will execute a new python process.

The other thing you could do is put the files in the same directory, and make the code that runs in game contained within a function, so that you can import it and than just call the function when you need it.

trevorKirkby
  • 1,886
  • 20
  • 47