Ram*_*hum 12 python python-import
我需要运行一个脚本foo.py,但我还需要在代码之前插入一些调试行来运行foo.py.目前我只是将这些行放入其中foo.py并且我小心不要将其提交给Git,但我不喜欢这个解决方案.
我想要的是一个单独的文件bar.py,我不承诺Git.然后我想跑:
python /somewhere/bar.py /somewhere_else/foo.py
Run Code Online (Sandbox Code Playgroud)
我想要做的是首先运行一些代码行bar.py,然后运行foo.py为__main__.它应该在bar.py线路运行的相同过程中,否则调试线将无济于事.
有没有办法bar.py做到这一点?
有人建议:
import imp
import sys
# Debugging code here
fp, pathname, description = imp.find_module(sys.argv[1])
imp.load_module('__main__', fp, pathname, description)
Run Code Online (Sandbox Code Playgroud)
问题是因为它使用导入机制,我需要在同一个文件夹foo.py上运行它.我不希望这样.我想简单介绍一下foo.py.
另外:解决方案也需要处理.pyc文件.
Jer*_*len 14
Python有一种在启动时运行代码的机制; 该网站的模块.
"This module is automatically imported during initialization."
Run Code Online (Sandbox Code Playgroud)
站点模块将尝试导入sitecustomize以前命名的模块__main__.它还将尝试导入usercustomize在您的环境指示的情况下命名的模块.
例如,您可以将sitecustomize.py文件放在包含以下内容的site-packages文件夹中:
import imp
import os
if 'MY_STARTUP_FILE' in os.environ:
try:
file_path = os.environ['MY_STARTUP_FILE']
folder, file_name = os.path.split(file_path)
module_name, _ = os.path.splitext(file_name)
fp, pathname, description = imp.find_module(module_name, [folder])
except Exception as e:
# Broad exception handling since sitecustomize exceptions are ignored
print "There was a problem finding startup file", file_path
print repr(e)
exit()
try:
imp.load_module(module_name, fp, pathname, description)
except Exception as e:
print "There was a problem loading startup file: ", file_path
print repr(e)
exit()
finally:
# "the caller is responsible for closing the file argument" from imp docs
if fp:
fp.close()
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样运行你的脚本:
MY_STARTUP_FILE=/somewhere/bar.py python /somewhere_else/foo.py
Run Code Online (Sandbox Code Playgroud)
__main__.export MY_STARTUP_FILE=/somewhere/bar.py,不需要每次都引用它execfile()如果文件是.py,则可以使用,如果文件是,则可以使用uncompyle2.pyc.
假设您的文件结构如下:
test|-- foo.py
|-- bar
|--bar.py
Run Code Online (Sandbox Code Playgroud)
foo.py
import sys
a = 1
print ('debugging...')
# run the other file
if sys.argv[1].endswith('.py'): # if .py run right away
execfile(sys.argv[1], globals(), locals())
elif sys.argv[1].endswith('.pyc'): # if .pyc, first uncompyle, then run
import uncompyle2
from StringIO import StringIO
f = StringIO()
uncompyle2.uncompyle_file(sys.argv[1], f)
f.seek(0)
exec(f.read(), globals(), locals())
Run Code Online (Sandbox Code Playgroud)
bar.py
print a
print 'real job'
Run Code Online (Sandbox Code Playgroud)
而在test/,如果你这样做:
$ python foo.py bar/bar.py
$ python foo.py bar/bar.pyc
Run Code Online (Sandbox Code Playgroud)
两者,输出相同:
debugging...
1
real job
Run Code Online (Sandbox Code Playgroud)
还请看这个答案.
| 归档时间: |
|
| 查看次数: |
3961 次 |
| 最近记录: |