In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article is to share with you the content of the sample analysis of the interface operation download file function implemented by Python integrated C #. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
First, what is this function?
I am very familiar with developing interfaces in C # & WinForm, and now I happen to have learned socket, the basic library of Python's network programming, so I thought of writing a program as follows:
When the program runs, it opens a WinForm form with:
Enter the address bar of the file download address
Select the file windowing button where the file is saved
The status area of the current download status
Download button
Enter the download address and select a location to save the file
Click the download button to download the file, and the status area shows the download status of the file, preferably the download progress
Put the interface to WinForm, and the download function to Python.
Second, the realization of the function of WinForm
WinForm is divided into several functions.
Interface design
Provide the public property of the download address
Provide public properties of file storage address
Provides a delegate definition for delegate download events
Provides a common way to record status information
Provide a common way to update progress information
1. Interface design
First we use VS to create a class library project
As for why .NET 5 or. Net core is not used, it is because: Python calls the C# dynamic link library
Create a new form after creating the project
In this example, the design interface is as follows:
two。 Method definition / current address / public string ThisUrl {get {return textUrl.Text;}} / current save path / public string ThisSavePath {get {return textSavePath.Text;}} / download event delegate / public event EventHandler DownloadEvent / / download button event / private void buttonDownload_Click (object sender, EventArgs e) {if (string.IsNullOrEmpty (this.textUrl.Text)) {MessageBox.Show ("Please enter the address of the file to download first!") ; this.textUrl.Focus (); return;} if (string.IsNullOrEmpty (this.textSavePath.Text)) {MessageBox.Show ("Please select the address to save the file first!") ; this.textSavePath.Focus (); return;} / / call delegate event if (this.DownloadEvent! = null) {this.DownloadEvent.Invoke (this, e);}}
An error will be reported when opening and selecting the save file path
Before you can call OLE, you must set the current thread to single-threaded unit (STA) mode. Make sure that your Main function is marked with STAThreadAttribute.
Very helpless, because our caller is not the Main function of C #, and I don't know how Python calls C # at present, so I can only think of another way, that is, open the window that chooses to save the file path to start a separate thread development, and mark STA on the child thread.
/ / Select button event / private void buttonSelect_Click (object sender, EventArgs e) {if (string.IsNullOrEmpty (this.textUrl.Text)) {MessageBox.Show ("Please enter the address of the file to download first!") ; this.textUrl.Focus (); return;} var index = this.textUrl.Text.LastIndexOf ("/"); var fileName = this.textUrl.Text.Substring (index + 1); Thread importThread = new Thread (() = > {var text = OpenDialog (fileName); MessageEvent (text);}); importThread.SetApartmentState (ApartmentState.STA); / / key importThread.Start () } / private string OpenDialog (string fileName) {var saveFileDialog = new SaveFileDialog (); saveFileDialog.Filter = "all files (*. *) | *. *"; saveFileDialog.FilterIndex = 0; if (! string.IsNullOrEmpty (fileName)) {saveFileDialog.FileName = Path.Combine (saveFileDialog.FileName, fileName);} DialogResult dialogResult = saveFileDialog.ShowDialog () If (dialogResult = = DialogResult.OK) {return saveFileDialog.FileName;} return String.Empty;} III. Python function implementation
The function of Python is divided into several parts
The program calls the .NET class library to open the form.
There is a function definition in the program that downloads the specified URL file and stores it to the specified path.
Function definition at the end of the program
Encapsulate the current program into a runnable program (e. G. exe in Windows)
Import socketimport timeimport remainapp = None# call update status information of dynamic link library def LogInfo (text): # print (text) mainapp.LogInfo (text) # call update download progress of dynamic link library def downloadInfo (c, all): mainapp.SetProcess (c, all) if c = = all: # LogInfo ("download progress {: .2f}" .format (c / all * 100)) LogInfo ("download complete") # else: # LogInfo ("download progress {: .2f}%" .format (c / all * 100)) # listen for download delegate event def Download (source Args): thisurl = source.ThisUrl.lower () thispath = source.ThisSavePath LogInfo ("download address: {}" .format (thisurl)) LogInfo ("save path is: {}" .format (thispath)) reobj = re.compile (r "(? xi)\ A [Amurz] [a-z0-9 +\ -.] *: / / # Scheme ([a-z0-9\ -. _%! $&'() * + =] + @)? # User ([a-z0-9\ -. _%] + # Named or IPv4 host |\ [a-z0-9\ -. _%! $&'() * + =:] +\]) # IPv6+ host "") match = reobj.search (thisurl) if match: HOST = match.group (2) PORT = 443if thisurl.startswith ('https') else 80 mysock = socket.socket (socket.AF_INET, socket.SOCK_STREAM) mysock.connect ((HOST) PORT)) urlend = 'GET {} HTTP/1.0\ r\ n\ r\ n'.format (thisurl). Encode () # LogInfo ("pass parameter: {}" .format (urlend)) LogInfo ("start downloading …") Mysock.sendall (urlend) count = 0 picture = b "" hearlength = 0 filelength = 0 hearc = b "while True: data = mysock.recv (5120) if (len (data))
< 1): break time.sleep(0.1) count = count + len(data) picture = picture + data # print(len(data), count) if hearlength == 0: hearlength = picture.find(b"\r\n\r\n") if hearlength >0: hearc = picture [: hearlength] .decode () # print (hearc) sear = re.search ('Content-Length: ([0-9] +)', hearc) if sear: filelength = int (sear.groups () [0]) downloadInfo (count-4-hearlength Filelength) else: downloadInfo (count-4-hearlength, filelength) mysock.close () # Skip past the header and save the picture data picture = picture [hearlength+4:] fhand = open (thispath "wb") fhand.write (picture) fhand.close () # Code: http://www.py4e.com/code3/urljpeg.py # Or select Download from this trinket's left-hand menu else: LogInfo ('download failed There is a problem with address format!') # introduce the dynamic link library import clr# by using pythonnet. Make sure that the dynamic link library files are placed in the current folder. If not, you should use this method # clr.AddReference ('D:\\ Path\\ DotNetWithPython') # clr.AddReference ('D:\\ Path\\ DotNetWithPython.dll') clr.AddReference ('DotNetWithPython') library * mainapp = MainForm () mainapp.DownloadEvent + = Downloadmainapp.ShowDialog () 4. Running effect
V. existing problems
The function has been realized, but there is an unsolvable problem, that is, when the file starts to download, the interface of WinForm will be stuck, which seems to be the reason why the main form is not opened with the current thread, but can not explain why there is no stutter at the beginning of the download. Thank you very much!
Thank you for reading! On the "Python integration C# implementation interface operation download file function example analysis" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, you can share it out for more people to see it!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.