Lenton
Lenton

Reputation: 519

Python 2.7. Save text file's name as date with linux command

I am using subprocess() to do linux shell commands in python and what i wanna do is read a file, get the needed info and save it in a text file named by current date. Reading and all works fine, but I don't know how to save file by naming it with current date. I tried making a variable with subprocess, but that was not successful.

def gauti():
        imti=tekstas.get("1.0", "end-1c")
        subprocess.call("data=$(date +"%d_%m_%Y")", shell=True)
        subprocess.call("grep -i '{imti}' /var/log/syslog > $data.txt".format(imti=imti), shell=True)

Upvotes: 0

Views: 48

Answers (1)

John Zwinck
John Zwinck

Reputation: 249123

This code will never work:

subprocess.call("data=$(date +"%d_%m_%Y")", shell=True)
subprocess.call("grep -i '{imti}' /var/log/syslog > $data.txt".format(imti=imti), shell=True)

Because a new shell is created every time, so your $data variable is not passed from the first command to the second. You can just do this:

subprocess.check_call("grep -i '{}' /var/log/syslog > $(date +%d_%m_%Y.txt)".format(imti), shell=True)

Upvotes: 2

Related Questions