Python 脚本独立工作但不在 crontab 中

Python Script working stand alone but not in crontab

我有一个 python 脚本,它调用 bash 脚本来获取上一小时创建的所有新目录的列表。 Python 脚本可执行。

    #!/usr/bin/python
import subprocess
import os
import dicom
import time

dire = '.'
directories = subprocess.check_output(
        ['find', '/dicom', '-maxdepth', '1', '-type', 'd', '-mmin', '-120', '-type', 'd', '-mmin', '+5']
).splitlines()
number_of_directories = len(directories)
b_new = 0
for n in range(1,number_of_directories):
    dire_str = str(directories[n])
    #dire_str = str(dire_str)
    print(dire_str)
    for dirpath,dirnames,filenames in os.walk(dire_str,topdown=True):
        a =1
        for filename in filenames:
            print(dirpath)
            if filename[-4:] == '.dcm':
                firstfilename = os.path.join(dirpath, filename)
                dcm_info = dicom.read_file(firstfilename, force=True)
                if dcm_info[0x0019, 0x109c].value == 'epiRTme':
                    dirpath_nii = dirpath[:-4]
            a = dirpath[-3:]
            a = int(a)
            os.chdir(dirpath_nii)
                    subprocess.call('/home/sdcme/bin/nii_mdir_sdcme %s %s' % (a, a), shell=True)
                break
            break

显然,如果我在命令提示符下独立调用此 python 脚本,它工作正常,但是当我在 crontab 上 60 分钟后将其设置为 运行 时,脚本会抛出以下错误:

Traceback (most recent call last):
  File "/home/sdcme/Final_concat_sdcme.py", line 9, in <module>
    ['find', '/dicom', '-maxdepth', '1', '-type', 'd', '-mmin', '-120', '-type', 'd', '-mmin', '+5']
  File "/usr/lib64/python2.7/subprocess.py", line 530, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "/usr/lib64/python2.7/subprocess.py", line 672, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.7/subprocess.py", line 1201, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
~    

Crontab 脚本

*/59 * * * * Final_concat_sdcme.py &>~concatenation.log

有人能指出这里的问题是什么吗。非常感谢帮助。

编辑:

Cron 输出日志错误:

niidicom_sdcme: Command not found.
niidicom_sdcme: Command not found.
niidicom_sdcme: Command not found.
niidicom_sdcme: Command not found.
niidicom_sdcme: Command not found.
niidicom_sdcme: Command not found.

实际上我的 python 脚本调用 nii_mdir_sdcme 脚本调用 niidicom_sdcme。当我 运行 上面的脚本在终端上独立时没有错误但是当 cron 作业调用上面的脚本->nii_mdir_sdcme->niidicom_sdcme 时似乎有问题。

恐怕您正在使用不包含 find 命令的路径覆盖 $PATH,是吗?

以下可能效果更好:

directories = subprocess.check_output(
        ['/usr/bin/find', '/dicom', '-maxdepth', '1', '-type', 'd', '-mmin', '-120', '-type', 'd', '-mmin', '+5']
).splitlines()