GVKun编程网logo

使用POST从Python脚本发送文件(python 发送post)

8

本篇文章给大家谈谈使用POST从Python脚本发送文件,以及python发送post的知识点,同时本文还将给你拓展C#使用IronPython库调用Python脚本、CentOS环境使用python

本篇文章给大家谈谈使用POST从Python脚本发送文件,以及python 发送post的知识点,同时本文还将给你拓展C#使用IronPython库调用Python脚本、CentOS环境使用python脚本备份文件、node.js – 从python脚本向节点脚本发送串行数据、Python-master,实用Python脚本合集!等相关知识,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

使用POST从Python脚本发送文件(python 发送post)

使用POST从Python脚本发送文件(python 发送post)

有没有一种方法可以使用Python脚本中的POST发送文件?

答案1

小编典典

通过请求,上传Multipart编码的文件非常简单:

with open(''report.xls'', ''rb'') as f:    r = requests.post(''http://httpbin.org/post'', files={''report.xls'': f})

而已。我不是在开玩笑-这是一行代码。文件已发送。让我们检查:

>>> r.text{  "origin": "179.13.100.4",  "files": {    "report.xls": "<censored...binary...data>"  },  "form": {},  "url": "http://httpbin.org/post",  "args": {},  "headers": {    "Content-Length": "3196",    "Accept-Encoding": "identity, deflate, compress, gzip",    "Accept": "*/*",    "User-Agent": "python-requests/0.8.0",    "Host": "httpbin.org:80",    "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"  },  "data": ""}

C#使用IronPython库调用Python脚本

C#使用IronPython库调用Python脚本

IronPython是一种在 .NET及 Mono上的 Python实现,由微软的 Jim Hugunin所发起,是一个开源的项目,基于微软的 DLR引擎。

IronPython的主页: IronPython.net /

github站点:

IronLanguages/ironpython3: Implementation of Python 3.x for .NET Framework that is built on top of the Dynamic Language Runtime. (github.com)

IronLanguages/ironpython2: Implementation of the Python programming language for .NET Framework; built on top of the Dynamic Language Runtime (DLR). (github.com)

方式一:适用于python脚本中不包含第三方模块的情况

1、执行语句

借由IronPython,就可以利用.NET执行存储在Python脚本中的代码段。下面通过简单的示例说明如何应用C#调用Python脚本。

1、在VS中新建窗体项目:IronPythonDemo

2、VS的菜单中打开“Nuget程序包管理器”

3、搜索IronPython程序包并安装

安装后自动引用如下的DLL

4、在exe程序所在文件夹下创建Python脚本。Python示例脚本实现求两个数的四则运算:

num1=arg1
num2=arg2
op=arg3
if op==1:
    result=num1+num2
elif op==2:
    result=num1-num2
elif op==3:
    result=num1*num2
else:
    result=num1*1.0/num2

设置IronPythonDemo.py文件属性为“复制到输出目录”

5、修改工程的配置文件App.config如下:

其中microsoft.scripting节点中设置了IronPython语言引擎的几个属性。

<?xml version="1.0" encoding="utf-8" ?>  
<configuration>  
  <configSections>  
    <section name="microsoft.scripting" type="Microsoft.Scripting.Hosting.Configuration.Section, Microsoft.Scripting"/>  
  </configSections>  
  <microsoft.scripting>  
    <languages>  
      <language names="IronPython;Python;py" extensions=".py" displayName="Python" type="IronPython.Runtime.PythonContext, IronPython"/>  
    </languages>  
  </microsoft.scripting>  
    <startup>   
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />  
    </startup>  
</configuration>

6、 绘制窗体如下:

7、编写计算的函数:

ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration();
ScriptEngine pyEngine = scriptRuntime.GetEngine("python");
ScriptSource source = pyEngine.CreateScriptSourceFromFile("IronPythonDemo.py");//设置脚本文件
ScriptScope scope = pyEngine.CreateScope();

try
{
    //设置参数
    scope.SetVariable("arg1", Convert.ToInt32(txtNum1.Text));
    scope.SetVariable("arg2", Convert.ToInt32(txtNum2.Text));
    scope.SetVariable("arg3", operation.SelectedIndex + 1);
}
catch (Exception)
{
    MessageBox.Show("输入有误。");
}

source.Execute(scope);
labelResult.Text = scope.GetVariable("result").ToString();
}

8、编译运行可得计算结果(此处未做输入的检查)

2、执行函数

IronPythonDemo2.py

def main(arr):
  try:
    arr = set(arr)
    arr = sorted(arr)
    arr = arr[0:]
    return str(arr)
  except Exception as err:
    return str(err)

c#代码

ScriptEngine pyEngine = IronPython.Hosting.Python.CreateEngine();//创建Python解释器对象
dynamic py = pyEngine.ExecuteFile(@"IronPythonDemo2.py");//读取脚本文件
int[] array = new int[9] { 9, 3, 5, 7, 2, 1, 3, 6, 8 };
string reStr = py.main(array);//调用脚本文件中对应的函数
MessageBox.Show(reStr);


//或者

ScriptRuntime pyRuntime = IronPython.Hosting.Python.CreateRuntime(); //创建一下运行环境
dynamic obj = pyRuntime.UseFile("IronPythonDemo2.py"); //调用一个Python文件
int[] array = new int[9] { 9, 3, 5, 7, 2, 1, 3, 6, 8 };
string reStr = obj.main(array);//调用脚本文件中对应的函数
MessageBox.Show(reStr);

方式二:适用于python脚本中包含第三方模块的情况

C#代码

using System;
using System.Collections;
using System.Diagnostics;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Process p = new Process();
            string path = "reset_ipc.py";//待处理python文件的路径,本例中放在debug文件夹下
            string sArguments = path;
            ArrayList arrayList = new ArrayList();
            arrayList.Add("com4");
            arrayList.Add(57600);
            arrayList.Add("password");
            foreach (var param in arrayList)//添加参数
            {
                sArguments += " " + sigstr;
            }

            p.StartInfo.FileName = @"D:\Python2\python.exe"; //python2.7的安装路径
            p.StartInfo.Arguments = sArguments;//python命令的参数
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();//启动进程

            Console.WriteLine("执行完毕!");

            Console.ReadKey();
        }
    }
}

python脚本

# -*- coding: UTF-8 -*-
import serial
import time

def resetIPC(com, baudrate, password, timeout=0.5):
    ser=serial.Serial(com, baudrate, timeout=timeout)
    flag=True
    try:
        ser.close()
        ser.open()
        ser.write("\n".encode("utf-8"))
        time.sleep(1)
        ser.write("root\n".encode("utf-8"))
        time.sleep(1)
        passwordStr="%s\n" % password
        ser.write(passwordStr.encode("utf-8"))
        time.sleep(1)
        ser.write("killall -9 xxx\n".encode("utf-8"))
        time.sleep(1)
        ser.write("rm /etc/xxx/xxx_user.*\n".encode("utf-8"))
        time.sleep(1)
        ser.write("reboot\n".encode("utf-8"))
        time.sleep(1)
    except Exception:
        flag=False
    finally:
        ser.close()
    return flag

resetIPC(sys.argv[1], sys.argv[2], sys.argv[3])

上面的python脚本实现的是重启IPC设备,测试功能成功。

调用包含第三方模块的python脚本时,尝试过使用path.append()方式,调试有各种问题,最终放弃了,没有研究。

到此这篇关于C#使用IronPython库调用Python脚本的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。

您可能感兴趣的文章:
  • IronPython连接MySQL的方法步骤
  • 在ironpython中利用装饰器执行SQL操作的例子
  • 使用IronPython把Python脚本集成到.NET程序中的教程
  • 推荐下python/ironpython:从入门到精通

CentOS环境使用python脚本备份文件

CentOS环境使用python脚本备份文件

备份脚本一

#!/usr/bin/python
#Filename:backup_ver1.py

importos
importtime

#1.Thefilesanddirectoriestobebackeduparespecifiedinalist.
source=['/home/swaroop/byte','/home/swaroop/bin']
#IfyouareusingWindows,usesource=[r'C:\Documents',r'D:\Work']orsomethinglikethat

#2.Thebackupmustbestoredinamainbackupdirectory
target_dir='/mnt/e/backup/'#Remembertochangethistowhatyouwillbeusing

#3.Thefilesarebackedupintoazipfile.
#4.Thenameoftheziparchiveisthecurrentdateandtime
target=target_dir+time.strftime('%Y%m%d%H%M%s')+'.zip'

#5.Weusethezipcommand(inUnix/Linux)toputthefilesinaziparchive
zip_command="zip-qr'%s'%s"%(target,''.join(source))

#Runthebackup
ifos.system(zip_command)==0:
print'Successfulbackupto',target
else:
print'BackupFailed'

备份脚本二

#!/usr/bin/python
#Filename:backup_ver2.py

importos
importtime

#1.Thefilesanddirectoriestobebackeduparespecifiedinalist.
source=['/home/swaroop/byte',r'D:\Work']orsomethinglikethat

#2.Thebackupmustbestoredinamainbackupdirectory
target_dir='/mnt/e/backup/'#Remembertochangethistowhatyouwillbeusing

#3.Thefilesarebackedupintoazipfile.
#4.Thecurrentdayisthenameofthesubdirectoryinthemaindirectory
today=target_dir+time.strftime('%Y%m%d')
#Thecurrenttimeisthenameoftheziparchive
Now=time.strftime('%H%M%s')

#Createthesubdirectoryifitisn'talreadythere
ifnotos.path.exists(today):
os.mkdir(today)#makedirectory
print'Successfullycreateddirectory',today

#Thenameofthezipfile
target=today+os.sep+Now+'.zip'

#5.Weusethezipcommand(inUnix/Linux)toputthefilesinaziparchive
zip_command="zip-qr'%s'%s"%(target,255);">备份脚本三 
#!/usr/bin/python
#Filename:backup_ver3.py

importos
importtime

#1.Thefilesanddirectoriestobebackeduparespecifiedinalist.
source=['/home/swaroop/byte',r'D:\Work']orsomethinglikethat

#2.Thebackupmustbestoredinamainbackupdirectory
target_dir='/mnt/e/backup/'#Remembertochangethistowhatyouwillbeusing

#3.Thefilesarebackedupintoazipfile.
#4.Thecurrentdayisthenameofthesubdirectoryinthemaindirectory
today=target_dir+time.strftime('%Y%m%d')
#Thecurrenttimeisthenameoftheziparchive
Now=time.strftime('%H%M%s')

#Takeacommentfromtheusertocreatethenameofthezipfile
comment=raw_input('Enteracomment-->')
iflen(comment)==0:#checkifacommentwasentered
target=today+os.sep+Now+'.zip'
else:
target=today+os.sep+Now+'_'+\
comment.replace('','_')+'.zip'
#Noticethebackslash!

#Createthesubdirectoryifitisn'talreadythere
ifnotos.path.exists(today):
os.mkdir(today)#makedirectory
print'Successfullycreateddirectory',today

#5.Weusethezipcommand(inUnix/Linux)toputthefilesinaziparchive
zip_command="zip-qr'%s'%s"%(target,target
else:
print'BackupFailed'

node.js – 从python脚本向节点脚本发送串行数据

node.js – 从python脚本向节点脚本发送串行数据

我有两个脚本 – 一个python脚本和另一个节点脚本.
python脚本在infinte循环中运行并读取串行数据.收到串行数据后,必须将其传递给node.js scipt,以便在节点服务器中处理.

我想使用node.js child_process模块​​从python脚本中读取数据,但由于python脚本是一个无限循环,它不会将任何数据返回到节点脚本.
谁能告诉我如何解决这个问题?

Python脚本:

import serial
ser = serial.Serial('COM10',9600,timeout =1)
while 1 :
    print ser.readline()'

Node.js脚本:

var spawn = require('child_process').spawn,ls    = spawn('python',['pyserial.py']);

ls.stdout.on('data',function (data) {
console.log('stdout: ' + data);
});

ls.stderr.on('data',function (data) {
console.log('stderr: ' + data);
});

注意:我使用python脚本的唯一原因是node.js由于serialport模块中的某些问题,serialport模块目前无法用于我的项目.

解决方法

打印后需要在python脚本中刷新标准输出流.这是打印时间的示例(我没有要测试的串行设备):

蟒蛇:

import sys
from datetime import datetime
from time import sleep
while 1:
    print datetime.Now()
    sys.stdout.flush()
    sleep(5)

Node.js的:

var spawn = require('child_process').spawn,['test.py']);

ls.stdout.on('data',function (data) {
    console.log('stdout: ' + data);
});

ls.stderr.on('data',function (data) {
    console.log('stderr: ' + data);
});

Python-master,实用Python脚本合集!

Python-master,实用Python脚本合集!

Python这门语言很适合用来写些实用的小脚本,跑个自动化、爬虫、算法什么的,非常方便。

这也是很多人学习Python的乐趣所在,可能只需要花个礼拜入门语法,就能用第三方库去解决实际问题。

我在Github上就看到过不少Python代码的项目,几十行代码就能实现一个场景功能,非常实用。

Python-master,实用Python脚本合集!

比方说仓库Python-master里就有很多不错的实用Python脚本,举几个简单例子:

1. 创建二维码

import pyqrcode
import png
from pyqrcode import QRCode

# Text which is to be converted to QR code
print("Enter text to convert")
s = input(": ")
# Name of QR code png file
print("Enter image name to save")
n = input(": ")
# Adding extension as .pnf
d = n + ".png"
# Creating QR code
url = pyqrcode.create(s)
# Saving QR code asa png file
url.show()
url.png(d, scale=6)
登录后复制

2. 从图片中截取文字

# extract text from a img and its coordinates using the pytesseract module
import cv2
import pytesseract

# You need to add tesseract binary dependency to system variable for this to work

img = cv2.imread("img.png")
# We need to convert the img into RGB format
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

hI, wI, k = img.shape
print(pytesseract.image_to_string(img))
boxes = pytesseract.image_to_boxes(img)
for b in boxes.splitlines():
b = b.split(" ")
x, y, w, h = int(b[1]), int(b[2]), int(b[3]), int(b[4])
cv2.rectangle(img, (x, hI - y), (w, hI - h), (0, 0, 255), 0.2)

cv2.imshow("img", img)
cv2.waitKey(0)
登录后复制

3. 判断闰年

def is_leap(year):
leap = False
if year % 4 == 0:
leap = True
if year % 100 == 0:
leap = False
if year % 400 == 0:
leap = True
return leap

year = int(input("Enter the year here: "))
print(is_leap(year))
登录后复制

4. 简易日历

from tkinter import *
import calendar

root = Tk()
# root.geometry("400x300")
root.title("Calendar")

# Function

def text():
month_int = int(month.get())
year_int = int(year.get())
cal = calendar.month(year_int, month_int)
textfield.delete(0.0, END)
textfield.insert(INSERT, cal)

# Creating Labels
label1 = Label(root, text="Month:")
label1.grid(row=0, column=0)

label2 = Label(root, text="Year:")
label2.grid(row=0, column=1)

# Creating spinbox
month = Spinbox(root, from_=1, to=12, width=8)
month.grid(row=1, column=0, padx=5)

year = Spinbox(root, from_=2000, to=2100, width=10)
year.grid(row=1, column=1, padx=10)

# Creating Button
button = Button(root, text="Go", command=text)
button.grid(row=1, column=2, padx=10)

# Creating Textfield
textfield = Text(root, width=25, height=10, fg="red")
textfield.grid(row=2, columnspan=2)

root.mainloop()
登录后复制

图片

5. 打印图片分辨率

def jpeg_res(filename):
 """"This function prints the resolution of the jpeg image file passed into it"""

 # open image for reading in binary mode
 with open(filename,''rb'') as img_file:

 # height of image (in 2 bytes) is at 164th position
 img_file.seek(163)

 # read the 2 bytes
 a = img_file.read(2)

 # calculate height
 height = (a[0] << 8) + a[1]

 # next 2 bytes is width
 a = img_file.read(2)

 # calculate width
 width = (a[0] << 8) + a[1]

 print("The resolution of the image is",width,"x",height)

jpeg_res("img1.jpg")
登录后复制

这个项目只是作者平时工作用到的一些小脚本,可能也会帮助到你。作者虽然不是程序员,但他这种用代码解决问题的习惯会极大的提升效率,也会迸发出更多的创新思维。我觉得这样的代码每个人都可以写出来,只要慢慢积累多练习就可以。

以上就是Python-master,实用Python脚本合集!的详细内容,更多请关注php中文网其它相关文章!

我们今天的关于使用POST从Python脚本发送文件python 发送post的分享已经告一段落,感谢您的关注,如果您想了解更多关于C#使用IronPython库调用Python脚本、CentOS环境使用python脚本备份文件、node.js – 从python脚本向节点脚本发送串行数据、Python-master,实用Python脚本合集!的相关信息,请在本站查询。

本文标签: