PHP调用Python脚本解决方案
我为你创建了一个PHP文件,用于调用你的pyt.py脚本并直接提供下载。同时,我也对你的Python脚本做了一些修改,使其能够接收参数。
修改后的pyt.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| import pandas as pd import sys
def process_files(input_file, output_file): try: sheet1 = pd.read_excel(input_file, sheet_name='Sheet1') export_data = pd.read_excel(input_file, sheet_name='导出数据')
sheet1_af_values = sheet1.iloc[:, 31]
matched_data = pd.DataFrame()
sheet1['胃肠'] = '否'
for index, af_value in enumerate(sheet1_af_values): matches = export_data[export_data['住院号'].astype(str) == str(af_value)] if not matches.empty: matched_data = pd.concat([matched_data, matches]) if len(matches) >= 2: sheet1.at[index, '胃肠'] = '是'
with pd.ExcelWriter(output_file) as writer: sheet1.to_excel(writer, sheet_name='Sheet1', index=False) matched_data.to_excel(writer, sheet_name='匹配数据', index=False) return True, "处理完成" except Exception as e: return False, f"处理失败: {str(e)}"
if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: python pyt.py <input_file> <output_file>") sys.exit(1) input_file = sys.argv[1] output_file = sys.argv[2] success, message = process_files(input_file, output_file) print(message) sys.exit(0 if success else 1)
|
PHP文件 (process_data.php)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
| <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>数据处理系统</title> <style> body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; line-height: 1.6; } h1 { color: text-align: center; } .form-group { margin-bottom: 20px; } label { display: block; margin-bottom: 5px; font-weight: bold; } .required:after { content: " *"; color: red; } input[type="file"] { width: 100%; padding: 8px; border: 1px solid border-radius: 4px; box-sizing: border-box; } button { background-color: color: white; padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; width: 100%; } button:hover { background-color: } .error { color: red; margin-bottom: 15px; padding: 10px; background-color: border: 1px solid border-radius: 4px; } .instructions { background-color: padding: 15px; border-left: 4px solid margin-bottom: 20px; } .file-inputs { background-color: padding: 15px; border-radius: 4px; margin-bottom: 20px; } </style> </head> <body> <?php ob_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') { ini_set('upload_max_filesize', '20M'); ini_set('post_max_size', '20M');
$error = ''; $outputFile = '结果_' . date('Ymd') . '.xlsx'; if (isset($_FILES['data_file'])) { $uploadedFile = $_FILES['data_file']['tmp_name'];
if (is_uploaded_file($uploadedFile)) { $pythonScript = 'pyt.py'; $command = escapeshellcmd("python3 $pythonScript \"$uploadedFile\" \"$outputFile\""); $output = shell_exec($command . " 2>&1");
if (file_exists($outputFile)) { ob_end_clean(); header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment; filename="' . basename($outputFile) . '"'); header('Content-Length: ' . filesize($outputFile)); ob_clean(); readfile($outputFile); unlink($outputFile); exit; } else { $error = "文件生成失败。<pre>Python 脚本输出: $output</pre>"; } } else { $error = "文件上传失败,请检查文件是否有效。"; } } else { $error = "请上传数据文件。"; } } ?> <h1>数据处理系统</h1> <div class="instructions"> <h3>使用说明:</h3> <ol> <li>上传包含Sheet1和导出数据的工作表(Excel格式)</li> <li>点击"提交"按钮生成处理结果</li> <li>系统会自动下载处理后的文件</li> </ol> <p><strong>注意:</strong>请确保上传的文件包含Sheet1和导出数据两个工作表。</p> </div> <?php if (!empty($error)): ?> <div class="error"><?php echo $error; ?></div> <?php endif; ?> <form action="" method="post" enctype="multipart/form-data"> <div class="file-inputs"> <div class="form-group"> <label for="data_file" class="required">数据文件:</label> <input type="file" name="data_file" id="data_file" required accept=".xls,.xlsx"> </div> </div> <button type="submit">提交并下载结果</button> </form> </body> </html>
|
使用说明
- 将修改后的
pyt.py和process_data.php放在同一目录下
- 确保服务器已安装Python和pandas库
- 访问
process_data.php页面
- 上传Excel文件并下载处理结果
主要修改点
Python脚本修改:
- 添加了命令行参数处理
- 改进了错误处理
- 将核心逻辑封装为函数
- 添加了返回状态和消息
PHP页面修改:
- 简化了表单,只需要上传一个文件
- 自动生成输出文件名
- 改进错误显示
- 确保正确处理文件下载
- 添加了临时文件清理
这个解决方案应该能满足你的需求,通过PHP调用Python脚本并直接提供下载功能。
时间: 2025-07-29T20:40:54
👤 用户
你好,我已经写好了代码pyt.py,目的是从两个xls文件中生成一个新的文件,我想把这个py文件通过php调用,并且像我给你的这个
时间: 2025-07-29T20:38:55
🤖 DeepSeek (deepseek-chat)
通过PHP调用Python脚本的解决方案
你想通过PHP调用已经
时间: 2025-07-29T20:38:55
👤 用户
你好,我已经写好了代码pyt.py,目的是从两个xls文件中生成一个新的文件,我想把这个py文件通过php调用,并生成一个直接下载文件。类似下面的这段代码。帮我生成一个php文件,通过pyt.py文件也帮我做好修改。
每月数据统计(上月本月对比)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
ini_set('upload_max_filesize', '20M');
ini_set('post_max_size', '20M');
$error = '';
// 验证输出文件名
if (empty($_POST['output_filename'])) {
$error = "请输入输出文件名";
} elseif (!preg_match('/^[a-zA-Z0-9_\-\x{4e00}-\x{9fa5}]+$/u', $_POST['output_filename'])) {
$error = "文件名只能包含中文、字母、数字、下划线和连字符";
} else {
$outputFile = trim($_POST['output_filename']) . '.xlsx';
if (isset($_FILES['file1']) && isset($_FILES['file2'])) {
$file1 = $_FILES['file1']['tmp_name'];
$file2 = $_FILES['file2']['tmp_name'];
if (is_uploaded_file($file1) && is_uploaded_file($file2)) {
$command = escapeshellcmd("python3 data_processor.py \"$file1\" \"$file2\" \"$outputFile\"");
$output = shell_exec($command . " 2>&1");
if (file_exists($outputFile)) {
ob_end_clean(); // 清空输出缓冲区
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="' . basename($outputFile) . '"');
header('Content-Length: ' . filesize($outputFile));
ob_clean(); // 再次清空输出缓冲区
readfile($outputFile);
exit;
} else {
$error = "文件生成失败。<pre>Python 脚本输出: $output</pre>";
}
} else {
$error = "文件上传失败,请检查文件是否有效。";
}
} else {
$error = "请上传两个文件。";
}
}
}
?>
<h1>每月数据统计(上月本月对比)</h1>
<div class="instructions">
<h3>使用说明:</h3>
<ol>
<li>上传上月数据文件(Excel格式)</li>
<li>上传本月数据文件(Excel格式)</li>
<li>指定输出文件名(默认为"对比结果")</li>
<li>点击"提交"按钮生成对比结果</li>
</ol>
<p><strong>注意:</strong>请确保上传的文件格式正确,且包含需要对比的数据。</p>
</div>
<?php if (!empty($error)): ?>
<div class="error"><?php echo $error; ?></div>
<?php endif; ?>
<form action="" method="post" enctype="multipart/form-data">
<div class="file-inputs">
<div class="form-group">
<label for="file1" class="required">上月数据文件:</label>
<input type="file" name="file1" id="file1" required accept=".xls,.xlsx">
</div>
<div class="form-group">
<label for="file2" class="required">本月数据文件:</label>
<input type="file" name="file2" id="file2" required accept=".xls,.xlsx">
</div>
</div>
<div class="form-group">
<label for="output_filename" class="required">输出文件名(不含扩展名):</label>
<input type="text" name="output_filename" id="output_filename" required
placeholder="对比结果"
pattern="[a-zA-Z0-9_\-\u4e00-\u9fa5]+"
title="只能包含中文、字母、数字、下划线和连字符">
</div>
<button type="submit">提交并下载结果</button>
</form>
时间: 2025-07-29T20:40:54
🤖 DeepSeek (deepseek-chat)
PHP调用Python脚本解决方案
我为你创建了一个PHP文件,用于调用你的pyt.py脚本并直接提供下载。同时,我也对你的Python脚本做了一些修改,使其能够接收参数。
修改后的pyt.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| import pandas as pd import sys
def process_files(input_file, output_file): try: sheet1 = pd.read_excel(input_file, sheet_name='Sheet1') export_data = pd.read_excel(input_file, sheet_name='导出数据')
sheet1_af_values = sheet1.iloc[:, 31]
matched_data = pd.DataFrame()
sheet1['胃肠'] = '否'
for index, af_value in enumerate(sheet1_af_values): matches = export_data[export_data['住院号'].astype(str) == str(af_value)] if not matches.empty: matched_data = pd.concat([matched_data, matches]) if len(matches) >= 2: sheet1.at[index, '胃肠'] = '是'
with pd.ExcelWriter(output_file) as writer: sheet1.to_excel(writer, sheet_name='Sheet1', index=False) matched_data.to_excel(writer, sheet_name='匹配数据', index=False) return True, "处理完成" except Exception as e: return False, f"处理失败: {str(e)}"
if __name__ == "__main__": if len(sys.argv) != 3: print("Usage: python pyt.py <input_file> <output_file>") sys.exit(1) input_file = sys.argv[1] output_file = sys.argv[2] success, message = process_files(input_file, output_file) print(message) sys.exit(0 if success else 1)
|
PHP文件 (process_data.php)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
| <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>数据处理系统</title> <style> body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; line-height: 1.6; } h1 { color: text-align: center; } .form-group { margin-bottom: 20px; } label { display: block; margin-bottom: 5px; font-weight: bold; } .required:after { content: " *"; color: red; } input[type="file"] { width: 100%; padding: 8px; border: 1px solid border-radius: 4px; box-sizing: border-box; } button { background-color: color: white; padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; width: 100%; } button:hover { background-color: } .error { color: red; margin-bottom: 15px; padding: 10px; background-color: border: 1px solid border-radius: 4px; } .instructions { background-color: padding: 15px; border-left: 4px solid margin-bottom: 20px; } .file-inputs { background-color: padding: 15px; border-radius: 4px; margin-bottom: 20px; } </style> </head> <body> <?php ob_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') { ini_set('upload_max_filesize', '20M'); ini_set('post_max_size', '20M');
$error = ''; $outputFile = '结果_' . date('Ymd') . '.xlsx'; if (isset($_FILES['data_file'])) { $uploadedFile = $_FILES['data_file']['tmp_name'];
if (is_uploaded_file($uploadedFile)) { $pythonScript = 'pyt.py'; $command = escapeshellcmd("python3 $pythonScript \"$uploadedFile\" \"$outputFile\""); $output = shell_exec($command . " 2>&1");
if (file_exists($outputFile)) { ob_end_clean(); header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment; filename="' . basename($outputFile) . '"'); header('Content-Length: ' . filesize($outputFile)); ob_clean(); readfile($outputFile); unlink($outputFile); exit; } else { $error = "文件生成失败。<pre>Python 脚本输出: $output</pre>"; } } else { $error = "文件上传失败,请检查文件是否有效。"; } } else { $error = "请上传数据文件。"; } } ?> <h1>数据处理系统</h1> <div class="instructions"> <h3>使用说明:</h3> <ol> <li>上传包含Sheet1和导出数据的工作表(Excel格式)</li> <li>点击"提交"按钮生成处理结果</li> <li>系统会自动下载处理后的文件</li> </ol> <p><strong>注意:</strong>请确保上传的文件包含Sheet1和导出数据两个工作表。</p> </div> <?php if (!empty($error)): ?> <div class="error"><?php echo $error; ?></div> <?php endif; ?> <form action="" method="post" enctype="multipart/form-data"> <div class="file-inputs"> <div class="form-group"> <label for="data_file" class="required">数据文件:</label> <input type="file" name="data_file" id="data_file" required accept=".xls,.xlsx"> </div> </div> <button type="submit">提交并下载结果</button> </form> </body> </html>
|
使用说明
- 将修改后的
pyt.py和process_data.php放在同一目录下
- 确保服务器已安装Python和pandas库
- 访问
process_data.php页面
- 上传Excel文件并下载处理结果
主要修改点
Python脚本修改:
- 添加了命令行参数处理
- 改进了错误处理
- 将核心逻辑封装为函数
- 添加了返回状态和消息
PHP页面修改:
- 简化了表单,只需要上传一个文件
- 自动生成输出文件名
- 改进错误显示
- 确保正确处理文件下载
- 添加了临时文件清理
这个解决方案应该能满足你的需求,通过PHP调用Python脚本并直接提供下载功能。
时间: 2025-07-29T20:40:54
对话统计