user
user

Reputation: 763

I want to have permission to write to a new file in a subdirectory in python, without using sudo

It's easy to find people asking how to do this, but there is never an answer that applies to me from what I can tell. I simply want to create permissions, in generality, to write to new files in a subdirectory. Within python I call

filename = 'dfs_err_results/err_results_st'+str(station_id)
file = open(filename,'w')
pickle.dump(results, file)
file.close()

but it fails at open() with IOError: [Errno 13] Permission denied: 'dfs_err_results/err_results_st5'. If I enter with sudo python, that error doesn't occur, but it's annoying to have to remember that and to have to check progress within sudo ps x where there are a ton of processes.

Am I correct there's no way to alter the subdirectory for future files using chmod? Or no way to have lines of code within the python script that set the permissions?

Thanks!

Upvotes: 0

Views: 1903

Answers (3)

Ella Cohen
Ella Cohen

Reputation: 1405

That's what worked for me:

os.chmod(filename, stat.S_IRWXO | stat.S_IRWXG | stat.S_IRWXU)
with open(filename, 'w') as f:
     pickle.dump(i, f)

this gives full permissions for everything you can choose the permissions you want by changing the stat mode: http://www.tutorialspoint.com/python/os_chmod.htm

Upvotes: 0

user
user

Reputation: 763

This is mostly contributed by xmp but it does require one more line to create the file:

subprocess.call(['/usr/bin/sudo', 'touch', filename])
subprocess.call(['/usr/bin/sudo', 'chmod', '777', filename])
file = open(filename,'w')
pickle.dump(results, file)
file.close()

Thanks for the help!

Upvotes: 0

xmp
xmp

Reputation: 114

Yes it does execute command with sudo. For exmaple, before openning the file you can change its write permission. Do whatever you need and change permission back. I don't have linux by hand at this moment, by try something like this:

subprocess.call(['/usr/bin/sudo', 'chmod', '777', filename])
with open(filename) as file:
    pickle.dump(results, file)

Upvotes: 3

Related Questions