我的工作是:我想创建一个Python脚本,自动更改文件的内容,然后在Perforce中提交更改。
因为这个文件一开始是只读的,所以我需要创建一个python脚本
- checkout 文件(以便编辑)
1.调用UpdateContent.cpp以更改该文件的内容
1.提交更改
更新内容.cpp
#include <iostream>
#include <string>
#include <stream>
#include <vector>
using namespace std;
const string YearKeyword = "YEAR";
const string ResourceInfoFileName = "//depot/Include/Version.h";
int main()
{
fstream ReadFile;
ReadFile.open(ResourceInfoFileName);
if (ReadFile.fail())
{
cout << "Error opening file: " << ResourceInfoFileName << endl;
return 1;
}
vector<string> lines; // a vector stores content of all the lines of the file
string line; // store the content of each line of the file
while (getline(ReadFile, line)) // read each line of the file
{
if (line.find(YearKeyword) != string::npos)
{
line.replace(line.size() - 5, 4, "2023"); // update current year
}
lines.push_back(line); // move the content of that line into the vector
}
ReadFile.close();
// after storing the content (after correcting) of the file into vector, we write the content back to the file
ofstream WriteFile;
WriteFile.open(ResourceInfoFileName);
if (WriteFile.fail())
{
cout << "Error opening file: " << ResourceInfoFileName << endl;
return 1;
}
for (size_t i = 0; i < lines.size() ; i++)
{
WriteFile << lines[i] << endl;
}
WriteFile.close();
return 0;
}
更新资源.py
from P4 import P4, P4Exception
import subprocess
p4 = P4()
print('User ', p4.user, ' connecting to ', p4.port)
print('Current workspace is ', p4.client)
try:
p4.connect()
versionfile = '//depot/Include/Version.h'
p4.run( "edit", versionfile )
cmd = "UpdateContent.cpp"
subprocess.call(["g++", cmd]) // **THIS IS ERROR POSITION (line 24)**
subprocess.call("./UpdateContent.out")
change = p4.fetch_change()
change._description = "Update information"
change._files = versionfile
p4.run_submit( change )
p4.disconnect()
print('Disconnected from server.')
except P4Exception:
for e in p4.errors:
print(e)
print('Script finished')
我把UpdateResource.py和UpdateContent.cpp放在N盘(N:/ResourceTools/)的同一个目录下,需要修改的Version.h
文件在另一个目录下,运行脚本时收到此消息。
我是python的新手,我错在哪里了?我猜是因为.cpp文件中的这行const string ResourceInfoFileName = "//depot/Include/Version.h";
(也许)。
1条答案
按热度按时间yeotifhr1#
您遇到的错误看起来像是在本地系统上安装
g++
失败。从Perforce/P4Python的Angular 来看,最简单的解决方案是完全抛弃C代码,而是将文件修改逻辑添加到Python脚本中,这样就不需要在一旁编译C应用程序(还要考虑Python脚本的运行环境,包括合适的编译器)。File I/O在Python中非常简单,因此您可以在四行Python代码中完成
UpdateContent.cpp
应用程序的全部工作。注意,我复制了C++代码的实现,其中假定年份是包含
YEAR
关键字的行的最后四个字符;您可以使用regex或str.replace
方法使其变得更加智能。