脚本编程实例分享怎么写

时间:2025-01-23 21:57:52 游戏攻略

脚本编程实例分享可以包括以下内容:

Shell 脚本实例

遍历文件夹中的图片文件

```bash

!/bin/bash

folder="/path/to/folder"

for file in "$folder"/*.png; do

if [ -f "$file" ]; then

filename=$(basename "$file")

extension="${filename*.}"

new_filename="${filename// /_}"

output_file="$folder/${new_filename%.*}.jpg"

convert "$file" -resize 800x600 "$output_file"

rm "$file"

echo "处理文件:$file -> $output_file"

fi

done

```

简单的 Shell 脚本

```bash

!/bin/bash

echo 'HelloWOlrd'

```

Python 脚本实例

打印数字和字符串

```python

!/usr/bin/python

i = 5

print(i)

i = i + 1

print(i)

s = 'welcome to my home!\nI will intorduce my family to you!'

print(s, i)

length = 6

width = 5

area = width * length

print('The Area is', area)

print('The perimeter is', 2 * (length + width))

for a in range(2, 9):

print(a)

else:

print('The loop is over!')

```

获取用户输入并打印最大值

```python

!/usr/bin/python

x = input('Enter the value of x: ')

def printMax(x, y):

if x > y:

print(x, 'is the maximum')

else:

print(y, 'is the maximum')

printMax(x, y)

```

实用脚本实例

文件备份脚本

```bash

!/bin/bash

source_dir="/path/to/source/directory"

backup_dir="/path/to/backup/directory"

for file in "$source_dir"/*; do

if [ -f "$file" ]; then

backup_file="$backup_dir/$(basename "$file")"

cp "$file" "$backup_file"

echo "备份文件: $file -> $backup_file"

fi

done

```

这些实例展示了如何使用 Shell 和 Python 编写简单的脚本,以完成一些常见的任务,如文件处理、用户输入和备份等。你可以根据自己的需求修改这些脚本,以适应不同的场景。