我有一个python文件,我不是维护者,看起来像下面的代码。如果不修改代码以将所有内容放在if __name__下,是否有办法从另一个模块导入它,以便我可以执行它并以编程方式传递参数?
import configargparse
if __name__ == '__main__':
args = get_args()
#more code to execute...
答案 0 :(得分:1)
You can't, for the most part. That code isn't exposed in a useful fashion. If you are able to modify the source file, the typical solution would be to move all of that code out of the if __name__ == '__main__'
block and put it into a main()
function instead.
It's possible to use the execfile
function to sort of do what you want, as described here内抓取数据,但由于多种原因,这是一个丑陋的解决方案(import
语句仅用于侧面效果,因为你是作弊并使用它来获取文件名,模块级变量可能不会像你期望的那样表现为module.var
,如该页面上的一些评论所述。)
即使在这个例子中,也不清楚是否有一种传递参数的有用方法。我猜你可以明确地设置sys.argv
,但看看它有多嗅到它已经闻到了......