我有一个定义函数的脚本,然后运行它
from datetime import timedelta
def foo():
return timedelta(days=2)
print(foo())
如果我打开一个shell并运行脚本,一切运行正常:
./manage.py shell
In [1]: %run web/the_script.py # Using Ipython
2 days, 0:00:00
但是当我将脚本作为./manage.py shell
的输入运行时(我希望将脚本作为cron
作业运行),它会像这样失败:
./manage.py shell < the_script.py
Traceback (most recent call last):
File "./manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/satan/Development/envs/p3_env/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/home/satan/Development/envs/p3_env/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/satan/Development/envs/p3_env/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/satan/Development/envs/p3_env/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/home/satan/Development/envs/p3_env/lib/python3.5/site-packages/django/core/management/commands/shell.py", line 101, in handle
exec(sys.stdin.read())
File "<string>", line 8, in <module>
File "<string>", line 5, in foo
NameError: name 'timedelta' is not defined
有人可以解释一下发生了什么吗?
答案 0 :(得分:0)
我之前看过这个问题,它有时只会从脚本执行第一行(或第一个函数)。这主要是因为在整个脚本执行过程中函数没有保持定义(或者是你的情况下的导入)。
试试这个:
./manage.py shell <<EOF\ execfile(the_script.py') \EOF
或者,如果它是Python 3 +
$ ./manage.py shell
...
>>> exec(open('./myscript.py').read())
不太好的解决方案:
echo 'import the_script' | python manage.py shell