subprocess.call() – เก่าแล้ว Older high-level API
ใช้ subprocess.check_call() , subprocess.run() แทน
ตัวอย่าง 1
echo คำว่า test1 test2 ลงไปที่ไฟล์ /tmp/out.txt
%python import subprocess e = 'echo "test1 test2" > /tmp/out.txt' subprocess.call(e, shell=True)
ตัวอย่าง 2
ตั้งชื่อไฟล์ของ log เป็นวันเวลาปัจจุบัน ไว้ใต้ /tmp แล้วใส่ข้อความ Hello World! ลงไป ด้วยการ echo
%python
import datetime
import subprocess
run_time = datetime.datetime.now() + datetime.timedelta(hours=7)
tmp_file = '/tmp/' + run_time.strftime("%Y-%m-%dT%H:%M:%S") + '.log'
print(tmp_file) # /tmp/2023-02-21T13:23:52.log
e = f'echo "Hello World!" >> {tmp_file}'
subprocess.call(e, shell=True)
ตรวจสอบว่าได้สร้างไฟล์ขึ้นมามั๊ย
%sh ls -l '/tmp/'
ดูเนื้อหาในไฟล์
%sh cat '/tmp/2023-02-21T13:23:52.log'
ใช้ Pandas อ่าน Text file
%python
import pandas as pd
# read text file
df = pd.read_fwf('/tmp/2023-02-21T14:55:00.log')
print(type(df))
print(df)
print(df.count())