我有一个脚本,我想在某些条件下提前退出:
if not "id" in dir():
print "id not set, cannot continue"
# exit here!
# otherwise continue with the rest of the script...
print "alright..."
[ more code ]
Run Code Online (Sandbox Code Playgroud)
我使用execfile("foo.py")Python交互式提示符运行此脚本,我希望脚本退出并返回到交互式解释器.我该怎么做呢?如果我使用sys.exit(),Python解释器完全退出.
python文档声明"execfile()不能可靠地用于修改函数的本地." 在页面http://docs.python.org/2/library/functions.html#execfile上
任何人都可以提供此声明的任何进一步细节吗 文档相当少.该语句似乎与"如果省略两个字典,表达式在调用execfile()的环境中执行非常矛盾." 这也在文档中.在函数中使用excecfile时是否存在特殊情况,然后execfile的作用类似于函数,因为它创建了一个新的作用域级别?
如果我在一个函数中使用execfile
def testfun():
execfile('thefile.py',globals())
def testfun2():
print a
Run Code Online (Sandbox Code Playgroud)
并且有'thefile.py'中的命令创建的对象(例如对象'a'),我怎么知道它们是testfun还是全局对象的本地对象?那么,在函数testfun2中,'a'似乎是全局的?如果我从execfile语句中省略了globals(),那么任何人都可以更详细地解释为什么'thefile.py'中的命令创建的对象不能用于'testfun'?
我有一个具有PREAMBLE信息的config.py脚本.我可以使用execfile()函数来读取配置文件的内容.
execfile("config.py")
print PREAMBLE
>>> "ABC"
Run Code Online (Sandbox Code Playgroud)
但是,当在方法中调用execfile()时,我有一个错误.
def a():
execfile("config.py")
print PREAMBLE
a()
>>> NameError: "global name 'PREAMBLE' is not defined"
Run Code Online (Sandbox Code Playgroud)
怎么了?怎么解决这个问题?
我想使用节点js执行exe。这是Windows命令提示符中命令的外观:
oplrun -D VersionId=3458 -de "output.dat" "Test.mod" "Test.dat"
Run Code Online (Sandbox Code Playgroud)
运行正常,我在output.dat文件中得到了输出。现在,我想使用nodejs执行相同的操作,为此我使用了execFile。如果我运行,它将运行正常:
var execFile = require('child_process').execFile;
execFile('oplrun',['Test.mod','Test.dat'], function(err, data) {
if(err) {
console.log(err)
}
else
console.log(data.toString());
});
Run Code Online (Sandbox Code Playgroud)
但是,如果我想将输出文件或版本作为参数传递,它将无法执行,并且也不会出现任何错误。这是代码:
var execFile = require('child_process').execFile;
var path ='D:\\IBM\\ILOG\SAMPLE\\output.dat';
execFile('oplrun', ['-de',path],['Test.mod','Test.dat'], function(err, data) {
if(err) {
console.log(err)
}
else
console.log(data.toString());
});
Run Code Online (Sandbox Code Playgroud)
如果需要传递-D VersionId = 1111或-de output.dat之类的参数,该如何传递参数。
谢谢阿吉斯