【问题标题】:exec() python command stops the whole executionexec() python 命令停止整个执行
【发布时间】:2021-10-27 08:50:14
【问题描述】:

我正在尝试运行一个脚本,该脚本会依次更改配置文件 (MET_config_EEv40.cfg) 中的一些参数,并运行一个脚本 ('IS_MET_EEv40_RAW.py') 来检索这些新的配置参数:

config_filename = os.getcwd() + '/MET_config_EEv40.cfg'

import sys
parser = configparser.ConfigParser()
parser.read('MET_config_EEv40.cfg')
parser.set('RAW', 'product', 'ERA')
parser.set('RAW', 'gee_product', 'ECMWF/ERA5_LAND/HOURLY')
parser.set('RAW', 'indicator', 'PRCP')
parser.set('RAW', 'resolution', '11110')


with open('MET_config_EEv40.cfg', 'w') as configfile:
    parser.write(configfile)

## execute file
import sys

os.system(exec(open('IS_MET_EEv40_RAW.py').read()))
#exec(open('IS_MET_EEv40_RAW.py').read())

print('I am here')

执行此操作后,我得到了预期的脚本输出:

Period of Reference: 2005 - 2019
Area of Interest: /InfoSequia/GIS/ink/shp_basin_wgs84.shp
Raw data is up to date. No new dates available in raw data
Press any key to continue . . .

但它从不打印结束行:I am here,这意味着在执行脚本后,算法终止。这不是我想要的,因为我希望能够更改一些其他配置参数并再次运行脚本。

由于这行代码,显示了该输出:

if (delta.days<=1):
    sys.exit('Raw data is up to date. No new dates available in raw data')

那么 sys.exit 是否会结束这两个进程?有什么想法可以在代码中替换 sys.exit() 以避免这种情况?

Im executing this file from a .bat file that contains the following:

@echo OFF

docker exec container python MET/PRCPmain.py

pause

【问题讨论】:

  • 您的IS_MET_EEv40_RAW.py 文件中有input 吗?
  • @Chillie 我认为没有。导入配置文件############################################## ##### config_general = configparser.RawConfigParser() config_filename = os.getcwd() + '/MET_config_EEV40.cfg' config_general.read(config_filename) ################# ####### 检索属性######################################## ##### # 通用属性 lot = config_general.get('GENERAL','lot') version = config_general.get('GENERAL','version') project_name = config_general.get('GENERAL','project_name')
  • Press any key to continue . . . 来自哪里?
  • 它只是接受带有get属性的参数并使用它们来执行功能

标签: python operating-system exec system


【解决方案1】:

exec(source, globals=None, locals=None, /)

在全局变量和局部变量的上下文中执行给定的源代码。

所以

import sys
exec("sys.exit(0)")
print("after")

和写一样

import sys
sys.exit(0)
print("after")

显然终止并且不打印afterexec 具有可选参数 globals,例如,您可以使用它来替代 sys

class MySys:
    def exit(self, *args):
        pass
exec("sys.exit(0)",{"sys":MySys()})
print("after")

哪个输出

after

因为它确实使用了来自 MySys 实例的 exit。如果您的代码使用了 sys 中的其他内容并希望它正常工作,您将需要在 MySys 类中模仿 sys 函数的方法

【讨论】:

  • 这很有用!谢谢!!
猜你喜欢
  • 2013-03-09
  • 2020-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-07
  • 2021-05-02
  • 2017-06-19
相关资源
最近更新 更多