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?

1
  • python util/file_reader.py C:/file_address? Commented Nov 13, 2015 at 10:54

1 Answer 1

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")
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.