Home > Blockchain >  Use shell script to run python code, but it return 'invalid syntax' and 'No module na
Use shell script to run python code, but it return 'invalid syntax' and 'No module na

Time:03-08

'invalid syntax' error occurs first.

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

I try to delete end=' 'code and run it again.

but it return another error: 'No module named' error

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

but it can run on Terminal successfully. Why?

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) code:

# 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 year0!=0 or year@0==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 script code:

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

system version:Ubuntu 18.04.4 LTS

CodePudding user response:

Your code is written for Python 3, but you're running it with a Python 2 interpreter.

If you want to use python3 instead of python, you need to specify that:

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

The exec is there for better performance (because it makes sh replace itself with Python instead of spawning a subprocess to exec the Python interpreter in) -- take exec out if python3 is ever no longer the last line of your script.

(using sh instead of bash because nothing you're doing here takes advantage of bash's features, and sh is faster to start).

  • Related