Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

cron - python script in cronjob not writing stdout to files

I have a python script which runs fine when started from a normal shell. The end result of the script is to run some commands using subprocess and write the output to many files When running via cron, the script runs but the files are never created, i know it runs since it logs some output to syslog, but i cant seem to make cron write to the files.

Here is the cron setup:

SHELL=/bin/bash
0 14 * * * echo 'source ~/venv/python3.8/bin/activate; python ~/scripts/myscript.py' | /bin/bash

Relevant part of the script:

for line in mylist:
    cmd = f"/usr/local/bin/bgpq3 -J -A -z {line}"
    filename = f"{line}.txt"
    logging.debug(f"Running {cmd}")
    ret = subprocess.run(
        cmd, shell=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
    )
    if ret.returncode == 0:
        f = open(filename, "w")
        f.write(ret.stdout)
        f.close()
    else:
        print(ret.stderr)
        logging.info(f"{ret.stderr} {line}")

The result could be many files created depending on the list. Like i said, this all works perfectly when kicked off from a normal shell, and the script runs when started with cron, but the files are never created / written.

thanks

question from:https://stackoverflow.com/questions/65921474/python-script-in-cronjob-not-writing-stdout-to-files

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

lol nevermind. It was writing the files to my home directory. I was expecting them to be in the same directory that i was running the script from


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...