2

I have a python file (my_code.py) in Home/Python_Codes folder in ubuntu. I want to run it in python shell. How can I do that?

I do this

>>> execfile('~/Python_Codes/my_code.py')

but it gives me path error

2
  • What's the exact, full path of the file? Home/Python_Codes doesn't make sense. Commented Jul 8, 2013 at 2:14
  • I gave you the folder structure in ubuntu. I can run my .py file in terminal using python ~/Python_Codes/my_code.py Commented Jul 8, 2013 at 2:26

4 Answers 4

6

You should expand tilde(~) to actual path. Try following code.

In Python 2.x:

import os
execfile(os.path.expanduser('~/Python_Codes/my_code.py'))

In Python 3.x (no execfile in Python 3.x):

import os
with open(os.path.expanduser('~/Python_Codes/my_code.py')) as f:
    exec(f.read())
Sign up to request clarification or add additional context in comments.

Comments

2

Importing your module will execute any code at the top indent level - which includes creating any functions and classes you have defined there.

james@Brindle:/tmp$ cat my_codes.py

def myfunc(arg1, arg2):
    print "arg1: %s, arg2: %s" % (arg1, arg2)

print "hello"
james@Brindle:/tmp$ python
Python 2.7.5 (default, Jun 14 2013, 22:12:26)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import my_codes
hello
>>> my_codes.myfunc("one", "two")
arg1: one, arg2: two
>>>

To add ~/Python_Codes to the list of places that python will search, you can manipulate sys.path to add that directory to the start of the list.

>>> import sys
>>> print sys.path
['', ... '/Library/Python/2.7/site-packages']
>>> sys.path.insert(0,'/home/me/Python_codes/')
>>> import my_codes

Comments

0

import os,then excute os.system('~/Python_Codes/my_code.py'),maybe you need to change the path('~/Python_Codes/my_code.py') into a absolute path

Comments

-1

Go to Run >> cmd >> change directory to your Python folder , remember to put your file my_file.py into that folder. For example: if your Python folder in C drive, type

cd C:\Python

then type this

python my_file.py

the system will run your file.

1 Comment

I think this answer belongs to a different question; it doesn't solve the actual problem being asked about. Namely, how to run another file while already at a prompt.

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.