我需要运行一个脚本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
文件.
我在桌面上创建了一个名为"headfirstpython"的文件夹,我需要将当前的工作目录更改为该文件夹及其内部的子文件夹.我使用os.getcwd()获取当前文件夹,它给了我'C\Python32'.我使用os.chdir('../ headfirstpython/chapter3')来更改目录,但它告诉它无法找到路径
>>> import os
>>> os.getcwd()
'C:\\Python32'
>>> os.chdir('../headfirstpython/chapter 3')
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
os.chdir('../headfirstpython/chapter 3')
WindowsError: [Error 3] The system cannot find the path specified: '../headfirstpython/chapter 3'
>>> os.chdir('../headfirstpython/chapter3')
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
os.chdir('../headfirstpython/chapter3')
WindowsError: [Error 3] The system cannot find the path specified: '../headfirstpython/chapter3'
>>>
Run Code Online (Sandbox Code Playgroud)