0

Right now I am using the import command to run other python files. But, O want to be able to run a python file in a different folder. How could I do this?

EDIT: I am using execfile, no help needed!

Thanks for the help :)

  • please see if [this SO QA](http://stackoverflow.com/questions/1186789/what-is-the-best-way-to-call-a-python-script-from-another-python-script) can help you out – Pynchia Sep 18 '15 at 21:10
  • please show how you run another python script which lies in the same directory – Pynchia Sep 18 '15 at 21:13
  • in case you need to execute the whole script, you can use `execfile('path/to/script.py')` (see the link in my first comment above). Otherwise, import the module and call the element you need (e.g. a function) – Pynchia Sep 18 '15 at 21:29
  • execfile solved my question – DatOneLefty Sep 21 '15 at 00:46
  • then if I were you, I'd update your accepted answer, removing the current one that uses `system`. That solution is overkill and certainly not a best-practice. If you want to mark the question as solved, I can post my comment as an answer. – Pynchia Sep 21 '15 at 06:55

2 Answers2

0

For a quick and dirty way to import a module from a specified path, check out the imp module: https://docs.python.org/2/library/imp.html

import imp

module_name = imp.load_source('module_name', '/path/to/module_name.py')
Nathaniel
  • 770
  • 7
  • 14
  • 1
    I think the OP is trying to run a python script. Though he says he's using the import command to do so. Not sure what the OP means by that. – Alea Kootz Sep 18 '15 at 21:00
  • @AustinKootz the answer is not misplaced. It allows you to call/access all the elements of the script. It is unclear if that is feasible or the script must be executed as a whole – Pynchia Sep 18 '15 at 21:33
  • OP was kind of unclear with what was wanted...this will call the script in the same way running it would, except that if there is a stanza protected by `if __name__ == '__main__':`, it won't be executed – Nathaniel Sep 19 '15 at 05:12
-2

I'll write a short code to demonstrate:

import os
# change the directory
os.chdir('c:\dir1\dir2')
# use os to send commands to shell or dos
os.system('python program.py')
# you are done

Seriously, it's that easy!

Alea Kootz
  • 913
  • 4
  • 11