Ubuntu 在pythonshell中运行python文件

Ubuntu 在pythonshell中运行python文件,ubuntu,python,Ubuntu,Python,我在ubuntu的Home/python\u Codes文件夹中有一个python文件(my\u code.py)。我想在pythonshell中运行它。我该怎么做 我知道 执行文件(“~/Python\u code/my\u code.py”) 但它给了我路径错误转到运行>>cmd>>将目录更改为Python文件夹,请记住将文件my_file.py放入该文件夹。例如:如果您的Python文件夹位于C驱动器中,请键入 cd C:\Python 然后打这个 python my_file.py

我在
ubuntu
Home/python\u Codes
文件夹中有一个python文件(
my\u code.py
)。我想在pythonshell中运行它。我该怎么做

我知道

执行文件(“~/Python\u code/my\u code.py”)


但它给了我路径错误

转到运行>>cmd>>将目录更改为Python文件夹,请记住将文件my_file.py放入该文件夹。例如:如果您的Python文件夹位于C驱动器中,请键入

cd C:\Python
然后打这个

python my_file.py
系统将运行您的文件。

您应该将波浪号(~)展开到实际路径。试试下面的代码

在Python 2.x中:

import os
execfile(os.path.expanduser('~/Python_Codes/my_code.py'))
在Python3.x中(Python3.x中没有
execfile
):


导入模块将在最高缩进级别执行任何代码,这包括创建您在其中定义的任何函数和类

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
>>>
要将
~/Python\u code
添加到Python将搜索的位置列表中,可以操纵
sys.path
将该目录添加到列表的开头

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

导入os,然后执行os.system(“~/Python\u code/my\u code.py”),可能需要将路径(“~/Python\u code/my\u code.py”)更改为绝对路径

文件的确切完整路径是什么
Home/Python\u code
没有意义。我给了你ubuntu中的文件夹结构。我可以使用
python~/python\u-Codes/my\u-code.py在终端中运行我的
.py
文件,我认为这个答案属于另一个问题;它不能解决被问及的实际问题。也就是说,如何在提示下运行另一个文件。
>>> import sys
>>> print sys.path
['', ... '/Library/Python/2.7/site-packages']
>>> sys.path.insert(0,'/home/me/Python_codes/')
>>> import my_codes