使用shell脚本到运行python代码,但是return'invalid syntax'和'No module named'错误

Use shell script to run python code, but it return 'invalid syntax' and 'No module named' error

'invalid syntax'首先出现错误。

lzh@ubuntu:~/Graduation_Project/Code$ bash test.sh
  File "/home/lzh/Graduation_Project/Code/update_day.py", line 27
    print(day_url,end='')
                     ^
SyntaxError: invalid syntax

我尝试删除 end=' ' 代码并再次 运行 它。

但它return另一个错误:'No module named'错误

Traceback (most recent call last):
  File "/home/lzh/Graduation_Project/Code/update_day.py", line 4, in <module>
    from urllib.request import urlopen
ImportError: No module named request

但它可以 运行 在终端上成功。为什么?

lzh@ubuntu:~/Graduation_Project/Code$ python /home/lzh/Graduation_Project/Code/update_day.py
https://vup.darkflame.ga/api/summary/2022/3/6   done

Python(3.6.9) 代码:

# coding: utf-8
#! /bin/env python3

from urllib.request import urlopen
import urllib
import pandas as pd
import time
tlist = time.localtime()
# column = ['date','income', 'pay_num','danmu']
try_times = 20
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}
year = tlist[0]
month = tlist[1]
day = tlist[2]
List = []
day_list = [31,0,31,30,31,30,31,31,30,31,30,31]
if day == 1:
    if month == 2:
        if (year%4 == 0 and year%100!=0 or year%400==0):
            day=29
        else:
            day=28
    else:
        day = day_list[month-1]

day_url = 'https://vup.darkflame.ga/api/summary/'+str(year)+'/'+str(month)+'/'+str(day-1)
print(day_url,end='')

shell脚本代码:

#! /bin/bash
#! /bin/env python3
python '/home/lzh/Graduation_Project/Code/update_day.py'

系统 version:Ubuntu 18.04.4 LTS

您的代码是为 Python 3 编写的,但您 运行 使用 Python 2 解释器。

如果您想使用 python3 而不是 python,您需要指定:

#!/bin/sh
exec python3 '/home/lzh/Graduation_Project/Code/update_day.py'

exec 是为了获得更好的性能(因为它使 sh 将自身替换为 Python 而不是生成子进程来执行Python 解释器输入) -- 如果 python3 不再是脚本的最后一行,则删除 exec

(使用 sh 而不是 bash 因为你在这里做的任何事情都没有利用 bash 的特性,而且 sh 启动速度更快)。