英文:
Why are my environmental variables adding whitespace?
问题
我正在运行Debian 12和Python 3.9.16。
test.env:
export TEST="ABC"
export SECONDTEST="DEF"
我运行了source test.env
然后尝试在Python中运行此脚本:
import os
test1 = os.getenv("TEST")
test2 = os.getenv("SECONDTEST")
def printenv(envvar):
print(envvar)
for char in envvar:
print(char)
print("done")
if envvar == "ABC" or envvar == "DEF":
print("ok!")
else:
print("Not ok!")
printenv(test1)
printenv(test2)
printenv(test1.rstrip())
环境变量在末尾添加了换行符。输出如下:
ABC
A
B
C
done
ok!
DEF
D
E
F
done
ok!
ABC
A
B
C
done
ok!
为什么我的环境变量中有换行字符?
英文:
I'm running Debian 12 and Python 3.9.16.
test.env:
export TEST="ABC"
export SECONDTEST="DEF"
I run source test.env
Then try to run this script in Python:
import os
test1 = os.getenv("TEST")
test2 = os.getenv("SECONDTEST")
def printenv(envvar):
print(envvar)
for char in envvar:
print(char)
print("done")
if envvar == "ABC" or envvar == "DEF":
print("ok!")
else:
print("Not ok!")
printenv(test1)
printenv(test2)
printenv(test1.rstrip())
The environmental variables add a new line character to the end. The output is:
A
B
C
done
Not ok!
DEF
D
E
F
done
Not ok!
ABC
A
B
C
done
ok!
Why are there newline characters in my environmental variables?
答案1
得分: 1
你的test.env
脚本中使用了MSWin的行结束符。这意味着每行都以$'\r'
结尾,该字符被附加到分配给变量的值后面。
运行fromdos
或dos2unix
来解决CR/LF问题。
英文:
You have MSWin line ends in the test.env
script. It means each line ends with a $'\r'
which is appended to the value assigned to a variable.
Run fromdos
or dos2unix
to fix the CR/LF issue.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论