Subhayan Bhattacharya
Subhayan Bhattacharya

Reputation: 5715

How to call and run a Python file inside another from a variable

I am using Python version : 2.6.6. I have a Python code test2.py inside directory : /home/admin.

And i am trying to run the file from inside : /home/admin/Practice/test.py.

My test.py code contains :

import os
filedir = os.path.realpath(__file__)
scriptdir = os.path.dirname(filedir)
print (filedir)
print (scriptdir)
newfile = scriptdir + "/../" + "test2.py"
new_module = __import__(newfile)
exec("python new_module 100 10"

Now i know this is probably not the right way to run a Python script from another. But when i run this i get :

[admin@centos1 Practice]$ python test.py
/home/admin/Practice/test.py
/home/admin/Practice
Traceback (most recent call last):
  File "test.py", line 7, in <module>
    new_module = __import__(newfile)
ImportError: Import by filename is not supported.

We have to run the Python script : /home/admin/test2.py which is inside the variable : newfile inside test.py.

Can someone please guide me as to how this should be done?

Thanks for the learning.

Upvotes: 1

Views: 121

Answers (2)

Arount
Arount

Reputation: 10403

I don't recommends to use execfile. In fact you just needs to learn how imports works in Python, you are learning Python right ?

You have several ways to handle this.

The easiest way is to package everything in a single module, saying mytest.

  1. Create a directory named mytest
  2. Create a file mytest/__init__.py (Why __init__.py)
  3. Copy your files: mytest/test.py, mytest/test2.py (you should change names too, but that is not the point here.)
  4. In your file mytest/test.py just do import test2 and all code in test2 will be executed.

A better way is to encapsulate code in test2.py within function like:

def foo():
    # your code here

So in test.py you can do:

import test2
test2.foo()

So assuming that your code in test2.py is:

print "Hello world!"

My proposal will result by something like:

file mytests/__init__.py empty.

file mytest/test.py:

import test2
test2.my_function_name()

file mytest/test2.py:

def my_function_name():
    print "Hello world!"

And you can run it with: python mytest/test.py

A last thing, you should rename the file test.py by __main__.py if you use it as command-line entry point (More about __main__).

Upvotes: 1

a_guest
a_guest

Reputation: 36249

You can run the contents of another Python file using the built-in function execfile. That is execfile(filename) executes the statements in the file which is pointed to by filename in the current scope.

Upvotes: 0

Related Questions