I was soberly addicted to calling awscli from a Python 2.7 script registered in crontab

Summary

--When calling from python, enter the command ʻaws cli with an absolute path. --/ usr / local / bin / aws s3 cp s3: //hoge/fuga/foo.txt bar.txt`.

I didn't use boto because I felt that I got an error because I only had access to the bottom of the bucket.

Thing you want to do

$ aws s3 cp s3://hoge/fuga/foo_20160711.txt .

I want to bring the file from S3. The file name changes every day depending on the date. If the download is successful, process the import, or something. I'm going to call it with python for the time being.

I tried it

fetch.py


import datetime
import os
import stat
import subprocess
import tempfile


def main():
	fd, tmp = tempfile.mkstemp()
    os.close(fd)
    os.chmod(tmp, stat.S_IRWXU | stat.S_IROTH)
    filename = 'foo_{}.txt'.format(datetie.datetime.now().strftime('%Y%m%d'))
    subprocess.check_call([
	    'aws',
     	's3',
	    'cp',
	    's3://hoge/fuga/{}'.format(filename),
		tmp,
    	'--quiet',
    ])
	do_something(tmp)

if __name__ == '__main__':
	main()

Make a code like this. I ran it from the command line and confirmed that it worked, so I threw it into crontab.

0 1 * * * /usr/local/bin/python /home/vagrant/fetch.py

It was no good.

Reasons not good

When I look at the execution history, I usually get an error. ʻIt is said that the aws command does not exist. By the way, I heard somewhere that the config file of ʻawscli is in the home directory, so the config cannot be read unless the home directory is specified exactly in the environment variable. However, since it is said that there is no ʻawscommand in the first place, we have not reached the problem of environment variables. Maybe there is noPATH. I think it can be solved by adding PATH` or specifying the location of the command directly.

Fix

--Add home directory to crontab --Pass environment variables to subprocess.check_call () --Search for the aws command with which and refer to it directly

HOME=/home/vagrant
0 1 * * * /usr/local/bin/python /home/vagrant/fetch.py

fetch.py


import datetime
import os
import stat
import subprocess
import tempfile


def do_something(name):
	return


def main():
	fd, tmp = tempfile.mkstemp()
    os.close(fd)
    os.chmod(tmp, stat.S_IRWXU | stat.S_IROTH)
    filename = 'foo_{}.txt'.format(datetie.datetime.now().strftime('%Y%m%d'))
    subprocess.check_call([
	    '/usr/local/bin/aws',
     	's3',
	    'cp',
	    's3://hoge/fuga/{}'.format(filename),
		tmp,
    	'--quiet',
    ], env=os.environ.copy())
	do_something(tmp)

if __name__ == '__main__':
	main()

It almost worked.

Recommended Posts

I was soberly addicted to calling awscli from a Python 2.7 script registered in crontab
A story that I was addicted to calling Lambda from AWS Lambda.
A story I was addicted to when inserting from Python to a PostgreSQL table
I was addicted to scraping with Selenium (+ Python) in 2020
What I was addicted to with json.dumps in Python base64 encoding
I wrote a function to load a Git extension script in Python
I wrote a script to extract a web page link in Python
I was addicted to confusing class variables and instance variables in Python
What I was addicted to Python autorun
When I tried to scrape using requests in python, I was addicted to SSLError, so a workaround memo
I was addicted to creating a Python venv environment with VS Code
Use Python from Java with Jython. I was also addicted to it.
The file name was bad in Python and I was addicted to import
I made a script in python to convert .md files to Scrapbox format
I was able to recurse in Python: lambda
I want to create a window in Python
Call a Python script from Embedded Python in C ++ / C ++
What I was addicted to when creating a web application in a windows environment
A note I was addicted to when running Python with Visual Studio Code
A story that I was addicted to when I made SFTP communication with python
I want to embed a variable in a Python string
I want to easily implement a timeout in python
I want to write in Python! (2) Let's write a test
I made a script to put a snippet in README.md
I tried to implement a pseudo pachislot in Python
A memorandum to run a python script in a bat file
I want to randomly sample a file in Python
I want to work with a robot in python.
A story that I was addicted to at np.where
Python script to create a JSON file from a CSV file
I was able to repeat it in Python: lambda
I was addicted to trying logging.getLogger in Flask 1.1.x
What I was addicted to when using Python tornado
Note that I was addicted to npm script not passing in the verification environment
I tried to create API list.csv in Python from swagger.yaml
I tried to implement a one-dimensional cellular automaton in Python
How to slice a block multiple array from a multiple array in Python
How to run a Python program from within a shell script
I want to start a lot of processes from python
I tried "How to get a method decorated in Python"
What I was addicted to when migrating Processing users to Python
I want to send a message from Python to LINE Bot
I wrote a script to get a popular site in Japan
I tried to make a stopwatch using tkinter in python
I tried changing the python script from 2.7.11 to 3.6.0 on windows10
I want to make input () a nice complement in python
[Fixed] I was addicted to alphanumeric judgment of Python strings
I made a script in Python to convert a text file for JSON (for vscode user snippet)
When I tried to install PIL and matplotlib in a virtualenv environment, I was addicted to it.
What I was addicted to when dealing with huge files in a Linux 32bit environment
I tried to create a Python script to get the value of a cell in Microsoft Excel
The story I was addicted to when I specified nil as a function argument in Go
I was a little addicted to installing Python3.3 + mod_wsgi3.4 on Sakura VPS (CentOS), so a retrospective memo
I wrote AWS Lambda, and I was a little addicted to the default value of Python arguments
How to pass arguments to a Python script in SPSS Modeler Batch
What I was addicted to when introducing ALE to Vim for Python
Post a message from IBM Cloud Functions to Slack in Python
A note I was addicted to when making a beep on Linux
How to get a string from a command line argument in python
I tried to implement a misunderstood prisoner's dilemma game in Python
I made a garbled generator that encodes favorite sentences from UTF-8 to Shift-JIS (cp932) in Python