简体   繁体   English

Python:For 循环仅打印列表的最后一个元素

[英]Python: For loops print only last element of a list

I am using a shared webspace and I can't install the dotenv libiary for php, but I can use the dotenv libiary for python to call enviorment variables from outside of my public directory and I also set the basedir for php, so that php can't access my .env file directly.我正在使用共享网站空间,我无法为 php 安装 dotenv 库,但我可以使用 python 的 dotenv 库从我的公共目录外部调用环境变量,我还为 php 设置了 basedir,这样 php 就可以' 直接访问我的.env文件。

To call my .env file with the secret keys, I run a bash.sh over the php function 'exec' and that bash.sh script calls/runs my python script to load the .env file.要使用密钥调用我的.env文件,我在 php function 'exec' 上运行 bash.sh 并且 bash.sh 脚本调用/运行我的 python 脚本以加载.env文件。 That works fine.那很好用。

But now, I want to print out all available enviorment varaibles through the python code with a for loop and I always just got the last element of the list.但是现在,我想通过带有 for 循环的 python 代码打印出所有可用的环境变量,而且我总是只得到列表的最后一个元素。

I also created a simple python test script, put it on my server and I got the same issue.我还创建了一个简单的 python 测试脚本,将它放在我的服务器上,我遇到了同样的问题。

PHP-File: PHP文件:

echo exec("./bashENV.sh", $error);

bashENV.sh: bashENV.sh:

#!/bin/bash
chmod +x ./testENV.py
python ./testENV.py

testENV.py:测试环境.py:

#!/usr/bin/env python
nums = [1 ,2, 3]
for num in nums:
    print(num)

If I run the python script on my local pc, it prints out 1,2,3.如果我在本地电脑上运行 python 脚本,它会打印出 1、2、3。 But on my shared webspace I only got the 3. It runs python 2.7.13 on the webserver and I can't install version 3.但是在我的共享网站空间上,我只得到了 3。它在网络服务器上运行 python 2.7.13,我无法安装版本 3。

Does anyone know, what is wrong with my code?有谁知道,我的代码有什么问题? Why the script prints only the last element?为什么脚本只打印最后一个元素?

Using exec like this will always print the last line of output generated by the shell command.像这样使用exec将始终打印 shell 命令生成的 output 的最后一行。 In your example, each line of the output generated by your python script will be stored in your $error variable (you have $error in the $output position ).在您的示例中,由您的 python 脚本生成的 output 的每一行都将存储在您的$error变量中(您在$output position中有$error )。 If you would prefer the output stored as one big string, you might try shell_exec如果您更喜欢将 output 存储为一个大字符串,您可以尝试shell_exec

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM