1

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.

2
  • did you tried with the following line: newfile = scriptdir + "/../" + "test2" Commented May 2, 2017 at 11:48
  • execfile is what you're looking for. Commented May 2, 2017 at 11:49

2 Answers 2

1

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__).

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.