简体   繁体   中英

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. Here is my problem:

I have a python .py executable file which creates multiple files and saves them to a directory. I need to run that file in a shell script. For some reason, the shell script executes the python script but no new files appear in my directory. When I just run the .py file, everything works fine

Here's what my shell script looks like:

    #!/bin/bash

    cd /home/usr/directory
    python myfile.py

Within my python script, the files that are saved are pickled object instances. 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:

When opening a file, it's preferable to use open() instead of invoking this constructor directly.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM