简体   繁体   中英

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.

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. 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.

I also created a simple python test script, put it on my server and I got the same issue.

PHP-File:

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

bashENV.sh:

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

testENV.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. 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.

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. 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 ). If you would prefer the output stored as one big string, you might try shell_exec

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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