python鋼琴塊自動腳本的簡單介紹

本文目錄一覽:

python開發命令行腳本

工作中會經常需要寫一些命令行腳本,如果還是用if,else判斷用戶輸入實在是太醜陋了。這裡介紹幾個python里的命令行腳本庫,可以幫助我們快速開發好用的命令行腳本。

使用方式是繼承Cmd,實現自己的子類。

參數comletekey是自動補全操作,默認值是Tab, 如果不為None 且readline可用的話,命令會自動完成。

這裡的readline指的是python實現的 GNU readline 接口(標準python庫里沒有,Windows系統不支持)。

參數stdin,stdout是輸入輸出流,默認是sys.stdin,sys.stout。

cmd提供了一個簡單的框架,但是功能比較簡單,python還有其他的很多第三方庫可以用來寫命令行程序。

這篇文章對比了各個庫的功能,貼在這裡:

看起來fire是最簡單的,來試一下。

fire 則是用一種面向廣義對象的方式來玩轉命令行,這種對象可以是類、函數、字典、列表等,它更加靈活,也更加簡單。你都不需要定義參數類型,fire 會根據輸入和參數默認值來自動判斷,這無疑進一步簡化了實現過程。

以下示例為 fire 實現的 計算器程序:

從上述示例可以看出,fire 提供的方式無疑是最簡單、並且最 Pythonic 的了。我們只需關注業務邏輯,而命令行參數的定義則和函數參數的定義融為了一體。

不過,有利自然也有弊,比如 nums 並沒有說是什麼類型,也就意味着輸入字符串’abc’也是合法的,這就意味着一個嚴格的命令行程序必須在自己的業務邏輯中來對期望的類型進行約束。

python自動化腳本怎麼編寫?

首先你需要在北鯤雲超算上申請python這款軟件,然後選擇配置後就可以直接開始作業了,運行軟件後就可以開始搭建腳本界面,編寫腳本代碼,用超算跑作業很方便,直接線上就可以使用,不需要下載到本地,而且計算效率非常的高。

教你如何在win10下自動運行python程序腳本

寫一個小的python程序,如test.py

由於python執行的比較快,窗口會一閃而過,所以加入while循環保持窗口。

在和test.py文件的同文件夾下 ,新建一個.bat文件,例如run.bat 這是由於python文件不是可執行文件,所以需要藉助bat文件進行操作。

第二行是執行這個test.py文件

右鍵單擊此電腦或我的電腦,點擊 管理 -系統工具 -任務計劃程序 -任務計劃程序庫

之後點擊右側創建基本任務

上述操作的圖就不放了,參考鏈接:

進入創建基本任務後,名稱隨意取,描述可選填,點擊下一步

觸發器,什麼時候觸髮腳本,這裡先選擇一次,點擊系一部之後選擇一次的時間,這裡往後寫幾分鐘,方便一會查看結果 點擊下一步

操作這裡默認啟動程序就可以,點擊下一步

選擇要執行的腳本文件,選擇瀏覽,選中run.bat文件點擊打開 ,點擊下一步

點擊完成

在任務計劃程序庫中找到剛才建立的 測試 任務,在右下方有屬性選項點擊,更改紅色圈出來的地方。 也可以在觸發器中更改觸發時間,或者新建觸發條件

等待觸發時間到,就會運行改腳本,按住Ctrl+C停止運行,測試成功

原文鏈接:

python 運維常用腳本

Python 批量遍歷目錄文件,並修改訪問時間

import os

path = “D:/UASM64/include/”

dirs = os.listdir(path)

temp=[];

for file in dirs:

temp.append(os.path.join(path, file))

for x in temp:

os.utime(x, (1577808000, 1577808000))

Python 實現的自動化服務器管理

import sys

import os

import paramiko

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def ssh_cmd(user,passwd,port,userfile,cmd):

def ssh_put(user,passwd,source,target):

while True:

try:

shell=str(input(“[Shell] # “))

if (shell == “”):

continue

elif (shell == “exit”):

exit()

elif (shell == “put”):

ssh_put(“root”,”123123″,”./a.py”,”/root/a.py”)

elif (shell ==”cron”):

temp=input(“輸入一個計劃任務: “)

temp1=”(crontab -l; echo “+ temp + “) |crontab”

ssh_cmd(“root”,”123123″,”22″,”./user_ip.conf”,temp1)

elif (shell == “uncron”):

temp=input(“輸入要刪除的計劃任務: “)

temp1=”crontab -l | grep -v ” “+ temp + “|crontab”

ssh_cmd(“root”,”123123″,”22″,”./user_ip.conf”,temp1)

else:

ssh_cmd(“lyshark”,”123123″,”22″,”./user_ip.conf”,shell)

遍歷目錄和文件

import os

def list_all_files(rootdir):

import os

_files = []

list = os.listdir(rootdir) #列出文件夾下所有的目錄與文件

for i in range(0,len(list)):

path = os.path.join(rootdir,list[i])

if os.path.isdir(path):

_files.extend(list_all_files(path))

if os.path.isfile(path):

_files.append(path)

return _files

a=list_all_files(“C:/Users/LyShark/Desktop/a”)

print(a)

python檢測指定端口狀態

import socket

sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

sk.settimeout(1)

for ip in range(0,254):

try:

sk.connect((“192.168.1.”+str(ip),443))

print(“192.168.1.%d server open \n”%ip)

except Exception:

print(“192.168.1.%d server not open”%ip)

sk.close()

python實現批量執行CMD命令

import sys

import os

import paramiko

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

print(“——————————\n”)

print(“使用說明,在當前目錄創建ip.txt寫入ip地址”)

print(“——————————\n”)

user=input(“輸入用戶名:”)

passwd=input(“輸入密碼:”)

port=input(“輸入端口:”)

cmd=input(“輸入執行的命令:”)

file = open(“./ip.txt”, “r”)

line = file.readlines()

for i in range(len(line)):

print(“對IP: %s 執行”%line[i].strip(‘\n’))

python3-實現釘釘報警

import requests

import sys

import json

dingding_url = ‘ ‘

data = {“msgtype”: “markdown”,”markdown”: {“title”: “監控”,”text”: “apche異常”}}

headers = {‘Content-Type’:’application/json;charset=UTF-8′}

send_data = json.dumps(data).encode(‘utf-8’)

requests.post(url=dingding_url,data=send_data,headers=headers)

import psutil

import requests

import time

import os

import json

monitor_name = set([‘httpd’,’cobblerd’]) # 用戶指定監控的服務進程名稱

proc_dict = {}

proc_name = set() # 系統檢測的進程名稱

monitor_map = {

‘httpd’: ‘systemctl restart httpd’,

‘cobblerd’: ‘systemctl restart cobblerd’ # 系統在進程down掉後,自動重啟

}

dingding_url = ‘ ‘

while True:

for proc in psutil.process_iter(attrs=[‘pid’,’name’]):

proc_dict[proc.info[‘pid’]] = proc.info[‘name’]

proc_name.add(proc.info[‘name’])

判斷指定端口是否開放

import socket

port_number = [135,443,80]

for index in port_number:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

result = sock.connect_ex((‘127.0.0.1’, index))

if result == 0:

print(“Port %d is open” % index)

else:

print(“Port %d is not open” % index)

sock.close()

判斷指定端口並且實現釘釘輪詢報警

import requests

import sys

import json

import socket

import time

def dingding(title,text):

dingding_url = ‘ ‘

data = {“msgtype”: “markdown”,”markdown”: {“title”: title,”text”: text}}

headers = {‘Content-Type’:’application/json;charset=UTF-8′}

send_data = json.dumps(data).encode(‘utf-8’)

requests.post(url=dingding_url,data=send_data,headers=headers)

def net_scan():

port_number = [80,135,443]

for index in port_number:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

result = sock.connect_ex((‘127.0.0.1’, index))

if result == 0:

print(“Port %d is open” % index)

else:

return index

sock.close()

while True:

dingding(“Warning”,net_scan())

time.sleep(60)

python-實現SSH批量CMD執行命令

import sys

import os

import paramiko

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def ssh_cmd(user,passwd,port,userfile,cmd):

file = open(userfile, “r”)

line = file.readlines()

for i in range(len(line)):

print(“對IP: %s 執行”%line[i].strip(‘\n’))

ssh.connect(hostname=line[i].strip(‘\n’),port=port,username=user,password=passwd)

cmd=cmd

stdin, stdout, stderr = ssh.exec_command(cmd)

result = stdout.read()

ssh_cmd(“lyshark”,”123″,”22″,”./ip.txt”,”free -h |grep ‘Mem:’ |awk ‘{print $3}'”)

用python寫一個列舉當前目錄以及所有子目錄下的文件,並打印出絕對路徑

import sys

import os

for root,dirs,files in os.walk(“C://”):

for name in files:

print(os.path.join(root,name))

os.walk()

按照這樣的日期格式(xxxx-xx-xx)每日生成一個文件,例如今天生成的文件為2013-09-23.log, 並且把磁盤的使用情況寫到到這個文件中。

import os

import sys

import time

new_time = time.strftime(“%Y-%m-%d”)

disk_status = os.popen(“df -h”).readlines()

str1 = ”.join(disk_status)

f = open(new_time+’.log’,’w’)

f.write(“%s”%str1)

f.flush()

f.close()

統計出每個IP的訪問量有多少?(從日誌文件中查找)

import sys

list = []

f = open(“/var/log/httpd/access_log”,”r”)

str1 = f.readlines()

f.close()

for i in str1:

ip=i.split()[0]

list.append(ip)

list_num=set(list)

for j in list_num:

num=list.count(j)

print(“%s —– %s” %(num,j))

寫個程序,接受用戶輸入數字,並進行校驗,非數字給出錯誤提示,然後重新等待用戶輸入。

import tab

import sys

while True:

try:

num=int(input(“輸入數字:”).strip())

for x in range(2,num+1):

for y in range(2,x):

if x % y == 0:

break

else:

print(x)

except ValueError:

print(“您輸入的不是數字”)

except KeyboardInterrupt:

sys.exit(“\n”)

ps 可以查看進程的內存佔用大小,寫一個腳本計算一下所有進程所佔用內存大小的和。

import sys

import os

list=[]

sum=0

str1=os.popen(“ps aux”,”r”).readlines()

for i in str1:

str2=i.split()

new_rss=str2[5]

list.append(new_rss)

for i in list[1:-1]:

num=int(i)

sum=sum+num

print(“%s — %s”%(list[0],sum))

關於Python 命令行參數argv

import sys

if len(sys.argv) 2:

print (“沒有輸入任何參數”)

sys.exit()

if sys.argv[1].startswith(“-“):

option = sys.argv[1][1:]

利用random生成6位數字加字母隨機驗證碼

import sys

import random

rand=[]

for x in range(6):

y=random.randrange(0,5)

if y == 2 or y == 4:

num=random.randrange(0,9)

rand.append(str(num))

else:

temp=random.randrange(65,91)

c=chr(temp)

rand.append(c)

result=””.join(rand)

print(result)

自動化-使用pexpect非交互登陸系統

import pexpect

import sys

ssh = pexpect.spawn(‘ssh lyshark@59.110.167.239’)

fout = file(‘sshlog.txt’, ‘w’)

ssh.logfile = fout

ssh.expect(“lyshark@59.110.167.239’s password:”)

ssh.sendline(“密碼”)

ssh.expect(‘#’)

ssh.sendline(‘ls /home’)

ssh.expect(‘#’)

Python-取系統時間

import sys

import time

time_str = time.strftime(“日期:%Y-%m-%d”,time.localtime())

print(time_str)

time_str= time.strftime(“時間:%H:%M”,time.localtime())

print(time_str)

psutil-獲取內存使用情況

import sys

import os

import psutil

memory_convent = 1024 * 1024

mem =psutil.virtual_memory()

print(“內存容量為:”+str(mem.total/(memory_convent))+”MB\n”)

print(“已使用內存:”+str(mem.used/(memory_convent))+”MB\n”)

print(“可用內存:”+str(mem.total/(memory_convent)-mem.used/(1024*1024))+”MB\n”)

print(“buffer容量:”+str(mem.buffers/( memory_convent ))+”MB\n”)

print(“cache容量:”+str(mem.cached/(memory_convent))+”MB\n”)

Python-通過SNMP協議監控CPU

注意:被監控的機器上需要支持snmp協議 yum install -y net-snmp*

import os

def getAllitems(host, oid):

sn1 = os.popen(‘snmpwalk -v 2c -c public ‘ + host + ‘ ‘ + oid + ‘|grep Raw|grep Cpu|grep -v Kernel’).read().split(‘\n’)[:-1]

return sn1

def getDate(host):

items = getAllitems(host, ‘.1.3.6.1.4.1.2021.11’)

if name == ‘ main ‘:

Python-通過SNMP協議監控系統負載

注意:被監控的機器上需要支持snmp協議 yum install -y net-snmp*

import os

import sys

def getAllitems(host, oid):

sn1 = os.popen(‘snmpwalk -v 2c -c public ‘ + host + ‘ ‘ + oid).read().split(‘\n’)

return sn1

def getload(host,loid):

load_oids = ‘1.3.6.1.4.1.2021.10.1.3.’ + str(loid)

return getAllitems(host,load_oids)[0].split(‘:’)[3]

if name == ‘ main ‘:

Python-通過SNMP協議監控內存

注意:被監控的機器上需要支持snmp協議 yum install -y net-snmp*

import os

def getAllitems(host, oid):

def getSwapTotal(host):

def getSwapUsed(host):

def getMemTotal(host):

def getMemUsed(host):

if name == ‘ main ‘:

Python-通過SNMP協議監控磁盤

注意:被監控的機器上需要支持snmp協議 yum install -y net-snmp*

import re

import os

def getAllitems(host,oid):

def getDate(source,newitem):

def getRealDate(item1,item2,listname):

def caculateDiskUsedRate(host):

if name == ‘ main ‘:

Python-通過SNMP協議監控網卡流量

注意:被監控的機器上需要支持snmp協議 yum install -y net-snmp*

import re

import os

def getAllitems(host,oid):

sn1 = os.popen(‘snmpwalk -v 2c -c public ‘ + host + ‘ ‘ + oid).read().split(‘\n’)[:-1]

return sn1

def getDevices(host):

device_mib = getAllitems(host,’RFC1213-MIB::ifDescr’)

device_list = []

def getDate(host,oid):

date_mib = getAllitems(host,oid)[1:]

date = []

if name == ‘ main ‘:

Python-實現多級菜單

import os

import sys

ps=”[None]-“

ip=[“192.168.1.1″,”192.168.1.2″,”192.168.1.3”]

flage=1

while True:

ps=”[None]-“

temp=input(ps)

if (temp==”test”):

print(“test page !!!!”)

elif(temp==”user”):

while (flage == 1):

ps=”[User]-“

temp1=input(ps)

if(temp1 ==”exit”):

flage=0

break

elif(temp1==”show”):

for i in range(len(ip)):

print(i)

Python實現一個沒用的東西

import sys

ps=”[root@localhost]# “

ip=[“192.168.1.1″,”192.168.1.2″,”192.168.1.3”]

while True:

temp=input(ps)

temp1=temp.split()

檢查各個進程讀寫的磁盤IO

import sys

import os

import time

import signal

import re

class DiskIO:

def init (self, pname=None, pid=None, reads=0, writes=0):

self.pname = pname

self.pid = pid

self.reads = 0

self.writes = 0

def main():

argc = len(sys.argv)

if argc != 1:

print (“usage: please run this script like [./lyshark.py]”)

sys.exit(0)

if os.getuid() != 0:

print (“Error: This script must be run as root”)

sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)

os.system(‘echo 1 /proc/sys/vm/block_dump’)

print (“TASK PID READ WRITE”)

while True:

os.system(‘dmesg -c /tmp/diskio.log’)

l = []

f = open(‘/tmp/diskio.log’, ‘r’)

line = f.readline()

while line:

m = re.match(

‘^(\S+)(\d+)(\d+): (READ|WRITE) block (\d+) on (\S+)’, line)

if m != None:

if not l:

l.append(DiskIO(m.group(1), m.group(2)))

line = f.readline()

continue

found = False

for item in l:

if item.pid == m.group(2):

found = True

if m.group(3) == “READ”:

item.reads = item.reads + 1

elif m.group(3) == “WRITE”:

item.writes = item.writes + 1

if not found:

l.append(DiskIO(m.group(1), m.group(2)))

line = f.readline()

time.sleep(1)

for item in l:

print (“%-10s %10s %10d %10d” %

(item.pname, item.pid, item.reads, item.writes))

def signal_handler(signal, frame):

os.system(‘echo 0 /proc/sys/vm/block_dump’)

sys.exit(0)

if name ==” main “:

main()

利用Pexpect實現自動非交互登陸linux

import pexpect

import sys

ssh = pexpect.spawn(‘ssh root@59.110.167.239’)

fout = file(‘sshlog.log’, ‘w’)

ssh.logfile = fout

ssh.expect(“root@59.110.167.239’s password:”)

ssh.sendline(“密碼”)

ssh.expect(‘#’)

ssh.sendline(‘ls /home’)

ssh.expect(‘#’)

利用psutil模塊獲取系統的各種統計信息

import sys

import psutil

import time

import os

time_str = time.strftime( “%Y-%m-%d”, time.localtime( ) )

file_name = “./” + time_str + “.log”

if os.path.exists ( file_name ) == False :

os.mknod( file_name )

handle = open ( file_name , “w” )

else :

handle = open ( file_name , “a” )

if len( sys.argv ) == 1 :

print_type = 1

else :

print_type = 2

def isset ( list_arr , name ) :

if name in list_arr :

return True

else :

return False

print_str = “”;

if ( print_type == 1 ) or isset( sys.argv,”mem” ) :

memory_convent = 1024 * 1024

mem = psutil.virtual_memory()

print_str += ” 內存狀態如下:\n”

print_str = print_str + ” 系統的內存容量為: “+str( mem.total/( memory_convent ) ) + ” MB\n”

print_str = print_str + ” 系統的內存以使用容量為: “+str( mem.used/( memory_convent ) ) + ” MB\n”

print_str = print_str + ” 系統可用的內存容量為: “+str( mem.total/( memory_convent ) – mem.used/( 1024*1024 )) + “MB\n”

print_str = print_str + ” 內存的buffer容量為: “+str( mem.buffers/( memory_convent ) ) + ” MB\n”

print_str = print_str + ” 內存的cache容量為:” +str( mem.cached/( memory_convent ) ) + ” MB\n”

if ( print_type == 1 ) or isset( sys.argv,”cpu” ) :

print_str += ” CPU狀態如下:\n”

cpu_status = psutil.cpu_times()

print_str = print_str + ” user = ” + str( cpu_status.user ) + “\n”

print_str = print_str + ” nice = ” + str( cpu_status.nice ) + “\n”

print_str = print_str + ” system = ” + str( cpu_status.system ) + “\n”

print_str = print_str + ” idle = ” + str ( cpu_status.idle ) + “\n”

print_str = print_str + ” iowait = ” + str ( cpu_status.iowait ) + “\n”

print_str = print_str + ” irq = ” + str( cpu_status.irq ) + “\n”

print_str = print_str + ” softirq = ” + str ( cpu_status.softirq ) + “\n”

print_str = print_str + ” steal = ” + str ( cpu_status.steal ) + “\n”

print_str = print_str + ” guest = ” + str ( cpu_status.guest ) + “\n”

if ( print_type == 1 ) or isset ( sys.argv,”disk” ) :

print_str += ” 硬盤信息如下:\n”

disk_status = psutil.disk_partitions()

for item in disk_status :

print_str = print_str + ” “+ str( item ) + “\n”

if ( print_type == 1 ) or isset ( sys.argv,”user” ) :

print_str += ” 登錄用戶信息如下:\n “

user_status = psutil.users()

for item in user_status :

print_str = print_str + ” “+ str( item ) + “\n”

print_str += “—————————————————————\n”

print ( print_str )

handle.write( print_str )

handle.close()

import psutil

mem = psutil.virtual_memory()

print mem.total,mem.used,mem

print psutil.swap_memory() # 輸出獲取SWAP分區信息

cpu = psutil.cpu_stats()

printcpu.interrupts,cpu.ctx_switches

psutil.cpu_times(percpu=True) # 輸出每個核心的詳細CPU信息

psutil.cpu_times().user # 獲取CPU的單項數據 [用戶態CPU的數據]

psutil.cpu_count() # 獲取CPU邏輯核心數,默認logical=True

psutil.cpu_count(logical=False) # 獲取CPU物理核心數

psutil.disk_partitions() # 列出全部的分區信息

psutil.disk_usage(‘/’) # 顯示出指定的掛載點情況【字節為單位】

psutil.disk_io_counters() # 磁盤總的IO個數

psutil.disk_io_counters(perdisk=True) # 獲取單個分區IO個數

psutil.net_io_counter() 獲取網絡總的IO,默認參數pernic=False

psutil.net_io_counter(pernic=Ture)獲取網絡各個網卡的IO

psutil.pids() # 列出所有進程的pid號

p = psutil.Process(2047)

p.name() 列出進程名稱

p.exe() 列出進程bin路徑

p.cwd() 列出進程工作目錄的絕對路徑

p.status()進程當前狀態[sleep等狀態]

p.create_time() 進程創建的時間 [時間戳格式]

p.uids()

p.gids()

p.cputimes() 【進程的CPU時間,包括用戶態、內核態】

p.cpu_affinity() # 顯示CPU親緣關係

p.memory_percent() 進程內存利用率

p.meminfo() 進程的RSS、VMS信息

p.io_counters() 進程IO信息,包括讀寫IO數及字節數

p.connections() 返回打開進程socket的namedutples列表

p.num_threads() 進程打開的線程數

import psutil

from subprocess import PIPE

p =psutil.Popen([“/usr/bin/python” ,”-c”,”print ‘helloworld'”],stdout=PIPE)

p.name()

p.username()

p.communicate()

p.cpu_times()

psutil.users() # 顯示當前登錄的用戶,和Linux的who命令差不多

psutil.boot_time() 結果是個UNIX時間戳,下面我們來轉換它為標準時間格式,如下:

datetime.datetime.fromtimestamp(psutil.boot_time()) # 得出的結果不是str格式,繼續進行轉換 datetime.datetime.fromtimestamp(psutil.boot_time()).strftime(‘%Y-%m-%d%H:%M:%S’)

Python生成一個隨機密碼

import random, string

def GenPassword(length):

if name == ‘ main ‘:

print (GenPassword(6))

python有哪些腳本

Python常用的30個腳本:

1、冒泡排序

2、計算x的n次方的方法

3、計算a*a + b*b + c*c + ……

4、計算階乘 n!

5、列出當前目錄下的所有文件和目錄名

6、把一個list中所有的字符串變成小寫:

7、輸出某個路徑下的所有文件和文件夾的路徑

8、輸出某個路徑及其子目錄下的所有文件路徑

9、輸出某個路徑及其子目錄下所有以.html為後綴的文件

10、把原字典的鍵值對顛倒並生產新的字典

相關推薦:《Python教程》

11、打印九九乘法表

通過指定end參數的值,可以取消在末尾輸出回車符,實現不換行。

12、替換列表中所有的3為3a

13、打印每個名字

** 善於使用 rang() ,會使問題變得簡單

14、合併去重

15、隨機生成驗證碼的兩種方式

16、計算平方根

17、判斷字符串是否只由數字組成

18、判斷奇偶數

19、判斷閏年

20、獲取最大值

21、斐波那契數列

斐波那契數列指的是這樣一個數列 0, 1, 1, 2, 3, 5, 8, 13;特別指出:第0項是0,第1項是第一個1。從第三項開始,每一項都等於前兩項之和。

22、十進制轉二進制、八進制、十六進制

23、最大公約數

23、最小公倍數

24、簡單計算器

25、生成日曆

26、文件IO

27、字符串判斷

28、字符串大小寫轉換

29、計算每個月天數

30、獲取昨天的日期

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/279098.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-20 15:02
下一篇 2024-12-20 15:02

相關推薦

  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29

發表回復

登錄後才能評論