[英]Running python script within a shell script: files don't save
I am very new to shell scripting, so I'm still figuring things out. 我对Shell脚本非常陌生,因此我仍在寻找解决方案。 Here is my problem: 这是我的问题:
I have a python .py executable file which creates multiple files and saves them to a directory. 我有一个python .py可执行文件,该文件可创建多个文件并将其保存到目录中。 I need to run that file in a shell script. 我需要在shell脚本中运行该文件。 For some reason, the shell script executes the python script but no new files appear in my directory. 由于某种原因,shell脚本执行了python脚本,但是我的目录中没有新文件出现。 When I just run the .py file, everything works fine 当我只运行.py文件时,一切正常
Here's what my shell script looks like: 这是我的shell脚本的样子:
#!/bin/bash
cd /home/usr/directory
python myfile.py
Within my python script, the files that are saved are pickled object instances. 在我的python脚本中,保存的文件是腌制的对象实例。 So every one of them looks something like this: 因此,每个人看起来都是这样的:
f = file('/home/usr/anotherdirectory/myfile.p','w')
pickle.dump(myObject,f)
f.close()
This line: 这行:
f = file('/home/usr/directory/myfile.p','w')
Should be: 应该:
f = open('/home/usr/directory/myfile.p','wb+')
For best practices it should be done like this: 为了获得最佳实践,应该这样进行:
with open('/home/usr/directory/myfile.p','wb+') as fs:
pickle.dump(myObject, fs)
The documentation for the file
function states: file
功能的文档指出:
When opening a file, it's preferable to use
open()
instead of invoking this constructor directly. 打开文件时,最好使用open()
而不是直接调用此构造函数。
Problems like this may be one of the reasons why. 这样的问题可能就是原因之一。 Try changing 尝试改变
f = file('/home/usr/directory/myfile.p','w')
to 至
f = open('/home/usr/directory/myfile.p','w')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.