Start job from python, redirect output to file

I have a script, update_file, that I typically run like so:

sudo update_file (file) > ./logs/(file) &

I was wondering what the proper syntax/is it possible, to call this script from within a Python script and still have it redirect output from update_file to a file and have it created as a system job.

EDIT: I should note, I run this against multiple (file)s so I would like to pass that as a variable.

Answers


First, the subprocess module is how you execute programs from Python. The section Replacing Older Functions with the subprocess Module in the documentation shows you how to transform typical shell functionality into Python.

Because you're using & to background the task, you'll want to create a Popen, and do the job-handling later. So:

jobs = []

# ... each time you want to run it on a file ...

jobs.append(subprocess.Popen(['sudo', 'update_file', file],
                             stdout=open(os.path.join('logs', file), 'w'))

# ... at exit time ...

for job in jobs:
    job.wait()
    job.stdout.close()

import subprocess

subprocess.call("sudo update_file(file)",stdout=open("logs/(file)","w"))

maybe?


Need Your Help

How to return a smart pointer?

c++ c++11 smart-pointers

I have a key, and a pointer to left and right nodes defined in a struct, in a class for a binary search tree.

cloning multiple VMs in parallel with multithreaded PowerCLI

vmware powercli

I've taken on the task of cloning a ton of VMs in VMware. Rather than clicking hundreds of times through the clone wizard, I'd like to automate this as much as possible.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.