3

I'm trying to run a program using spyder instead of ipython notebook because it currently runs faster. The data is imported and extracted using

run util/file_reader.py C:/file_address

Obviously the run command doesn't work in normal python and I can't find an equivalent, I've looked at the various how to replace ipython magic commands Q&As on here and generally but I can't find one for the run command...

Is there a module or set of code that would work as an equivalent in normal python?

Mangu Singh Rajpurohit
  • 10,806
  • 4
  • 68
  • 97
aml
  • 137
  • 9

1 Answers1

2

What you want is a bit weird. Precisely, the run magic runs the given file in the current ipython namespace as if it were the __main__ module. To get precisely the same effects would require a bit of effort.

with open("util/file_reader.py") as f:
    src = f.read()

# set command line arguments
import sys
sys.argv = ["file_reader.py", "C:/file_address"]

# use "__main__.py" as file name, so module thinks its the main module
code = compile(src, "__main__.py", "exec")
exec(code)

If would be easier and better to define a main function in file_reader.py and then call that at the end of the file if an if __name__ == "__main__":

eg.

util/file_reader.py

def main(filename):
    print(filename)

if __name__ == "__main__":
    import sys
    main(sys.argv[1])

So now you can easily run the code in this module by importing it and then calling the main function.

eg.

import util.file_reader

util.file_reader.main("C:/file_address")
Dunes
  • 37,291
  • 7
  • 81
  • 97
  • This makes sense, but the file_reader already has a if __name__ == "__main__" function, and it contains RM = read_file(sys.argv[1]) d = RM.resi(1) where read_file is a class defined in file_reader and resi is a method within that class. but calling main errors (because there isn't a main function) and if I put the code into a 'main' function it beings up a list index error... The file reader contains two classes and the "if _name...". It's not clear how to call them from normal python in a functioning manner. – aml Nov 16 '15 at 09:40