2013-07-08 55 views
2

我在ubuntuHome/Python_Codes文件夾中有一個python文件(my_code.py)。我想在python shell中運行它。我怎樣才能做到這一點?在python shell中運行python文件

我做this

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

,但它給了我路徑錯誤

+0

文件的確切路徑是什麼? 'Home/Python_Codes'沒有意義。 – user2357112

+0

我給你在Ubuntu的文件夾結構。我可以在終端使用'python〜/ Python_Codes/my_code.py'運行我的'.py'文件 – Darshana

回答

6

您應該將代字號(〜)展開爲實際路徑。嘗試下面的代碼。

在Python 2.x中:

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

在Python 3.x中(在Python 3.X沒有execfile):

import os 
with open(os.path.expanduser('~/Python_Codes/my_code.py')) as f: 
    exec(f.read()) 
-1

去跑>> CMD >>目錄更改爲Python的文件夾,記得把你的文件my_file.py成該文件夾。例如:如果你的Python文件夾在C盤,類型

cd C:\Python 

然後鍵入此

python my_file.py 

系統將運行您的文件。

+0

我認爲這個答案屬於另一個問題;它並沒有解決被問到的實際問題。即,如何在提示時運行另一個文件。 –

2

導入您的模塊將在頂部縮進執行任何代碼級別 - 其中包括創建您在那裏定義的任何函數和類。

[email protected]:/tmp$ cat my_codes.py 

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

print "hello" 
[email protected]:/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 
>>> 

要添加到~/Python_Codes場所的列表蟒蛇將搜索,你可以操縱sys.path到該目錄添加到列表的開始。

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

進口的操作系統,然後EXCUTE使用os.system( '〜/ Python_Codes/my_code.py'),也許你需要改變路徑( '〜/ Python_Codes/my_code.py')成絕對路徑