在python shell中运行python文件

Dar*_*ana 2 python ubuntu

my_code.pyHome/Python_Codes文件夹中有一个python文件()ubuntu.我想在python shell中运行它.我怎样才能做到这一点?

我做这个

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

但它给了我路径错误

fal*_*tru 6

您应该将波浪号(〜)扩展为实际路径.请尝试以下代码.

在Python 2.x中:

import os
execfile(os.path.expanduser('~/Python_Codes/my_code.py'))
Run Code Online (Sandbox Code Playgroud)

在Python 3.x中(Python 3.x中没有execfile):

import os
with open(os.path.expanduser('~/Python_Codes/my_code.py')) as f:
    exec(f.read())
Run Code Online (Sandbox Code Playgroud)