当从Python传递到C++并返回到Python时,如何保存文字

2024-09-30 12:11:20 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,就这样吧。我有一个用Python编写日志的程序。我希望当程序不使用它时,这个日志是安全的,所以我编写了一个Python脚本,它创建了C++源,它设计为将日志重印回Python。一旦我编译了这个源代码,我就可以让日志非常安全,然后运行可执行文件来检索它。它很复杂,但很管用

问题:当我创建Python日志时,我将'替换为等价的文本(\'),这样在存储字符串时它不会破坏我的字符串。但是,当我用C++来拾取这个词并把它放回原处时,我就失去了字面,所以我得到了坏的字符串。是否有一个简单的方法来替换C++中的^ {CD1}},而相应的文字与Python中的^ {< CD4}函数类似。在

一些可能有帮助的代码片段:

如何用Python将字符串写入日志

logFile.write("    '{}'".format(somestring.replace("'","\\'").encode('ascii', 'ignore'))

Python日志的外观:

^{pr2}$

如何编写从日志中的Python(Cr {}是^ {CD5>})

存储字符串的C++行
CFile.write('    CR{}.somestring = "{}";\n'.format(num,somestring))
<存储字符串的C++行的结尾看起来像

CR0.somestring = "This is a string and it doesn't keep track of literals";

将字符串写入Python(文件名为^ {CD6>})

的C++行
CRPYLog << "    '" + CR0.somestring + "'," << endl;

这是当它被打印回Python日志中时的样子

'This is a string and it doesn't keep track of literals'

上面的行在语法上无效,因此当我尝试使用Python日志时,它将中断


Tags: andof字符串程序formatstringisit
2条回答

为了解决您的主要目标,即使应用程序的“日志在程序不使用时不受编辑”,我建议您坚持使用为相同目的而设计的常用标准工具。在

例如,添加digital signature

A digital signature is a mathematical scheme for demonstrating the authenticity of a digital message or document. A valid digital signature gives a recipient reason to believe that the message was created by a known sender, such that the sender cannot deny having sent the message (authentication and non-repudiation) and that the message was not altered in transit (integrity). Digital signatures are commonly used for software distribution, financial transactions, and in other cases where it is important to detect forgery or tampering.

和/或encrypt文件:

In cryptography, encryption is the process of encoding messages (or information) in such a way that third parties cannot read it, but only authorized parties can.

这两种方法都是加密方法,如果使用的(私有)加密密钥被有效地保密,那么很难不被检测地更改文件内容。在


在Python中,两种方法都可以使用GnuPGpython-gnupg):

The gnupg module allows Python programs to make use of the functionality provided by the GNU Privacy Guard (abbreviated GPG or GnuPG). Using this module, Python programs can encrypt and decrypt data, digitally sign documents and verify digital signatures, manage (generate, list and delete) encryption keys, using proven Public Key Infrastructure (PKI) encryption technology based on OpenPGP.

我自己没有使用过这个Python库,但是GnuPG本身有点标准,例如,用于确保电子邮件通信或linux包分发的安全。在

请注意,您可能需要一个数字签名,即使您已经用这种方式加密了文件。这是因为加密使用了public key,根据定义,这是公共的。在非对称密码学中,需要(秘密)私钥来解码密文并创建数字签名,即验证接收者(加密)和发送者(签名)的身份。在


如果您想使用encryption plus integrity check,请查看以下库:


也就是说,当您的操作系统的访问控制机制提供的保护足够时,您就可以限制性地配置它们并依赖于它。(也不需要进行密码检查。)

<强>有一种简单的方法来替换C++中的与对应于Python中的替换函数的文字,>/P>

实际上是的,您可以使用Boost库来实现这一点。在

#include <boost/algorithm/string.hpp> 

std::string some_string("Your string");
boost::replace_all(some_string, "Your", "My");

相关问题 更多 >

    热门问题