python脚本运行上下行第1节

本文详细介绍了Python中环境变量的设置与读取方法,包括os.environ的使用及shell变量的操作。同时,深入探讨了Python的标准输入输出流,如sys.stdin、sys.stdout和sys.stderr的使用方式,并通过具体实例展示了如何进行文件输入输出处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python脚本运行上下行第1节


1、#os.getcwd和sys.path 打印模块的搜索路径

C:\Windows\System32>type whereami.py                                                                                    

#!/usr/bin/env python

import os,sys                                                                                                           

print('my os.getcwd=>',os.getcwd())

print('my sys.path=>',os.path[:6])                                                                                      

input()


2、#os.getcwd和sys.path输出设置的路径和path实际路径

c:\Windows\System32>python                     

Python 3.6.5rc1 (v3.6.5rc1:f03c5148cf, Mar 14 2018, 03:12:11) [MSC v.1913 64 bit (AMD64)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>> import os,sys                                                                                 

>>> print('my os.getcwd=>',os.getcwd())                                                           

my os.getcwd=> c:\Windows\System32                                    

>>> print('my sys.path=>',sys.path[:6])        

my sys.path=> ['', 'C:\\Program Files\\Python36\\python36.zip', 'C:\\Program Files\\Python36\\DLLs', 'C:\\Program Files\

\Python36\\lib', 'C:\\Program Files\\Python36', 'C:\\Program Files\\Python36\\lib\\site-packages']


3、#whereami.py脚本使用相对路径进行输出

c:\Windows\System32\temp>python ..\whereami.py                                                                          

my os.getcwd => c:\Windows\System32\temp

my sys.path => ['c:\\Windows\\System32', 'C:\\Program Files\\Python36\\python36.zip', 'C:\\Program Files\\Python36\\DLLs

', 'C:\\Program Files\\Python36\\lib', 'C:\\Program Files\\Python36', 'C:\\Program Files\\Python36\\lib\\site-packages']

quit()     


4、#sys.argv没有任何参数被传入所以空字符输出

>>> import sys                                                                                    

>>> sys.argv                                                                                                            

['']       


5、#testargv.py脚本输出以列表形式

c:\python>python testargv.py                                                                                            

['testargv.py']                                                                                                         


c:\python>python testargv.py spam eggs cheese                                                                           

['testargv.py', 'spam', 'eggs', 'cheese']                                                                               


c:\python>python testargv.py -i data.txt -o results.txt                                                                 

['testargv.py', '-i', 'data.txt', '-o', 'results.txt'] 


6、#testargv2.py脚本输出以列表形式

testargv2.py代码如下:

#!/usr/bin/env python

"collect command-line options in a dictionary"


def getopts(argv):

opts = {}

while argv:

if argv[0][0] == '-':     ​    ​#this is "-" name

opts[argv[0]] = argv[1] #dict is parameter '-' name

argv = argv[2:]

else:

argv = argv[1:]

return opts


if __name__=='__main__':

from sys import argv #client code

myargs = getopts(argv)

if '-i' in myargs:

print(myargs['-i'])

print(myargs)


执行代码:

c:\python>python testargv2.py -i data.txt -o results.txt                                                                

data.txt                                                                                                                

{'-i': 'data.txt', '-o': 'results.txt'} 


7、#os.environ.keys()输出shell变量

>>> import os                                    

>>> os.environ.keys()   


>>> list(os.environ.keys())                                                                                             

['ALLUSERSPROFILE', 'APPDATA', 'COMMONPROGRAMFILES', 'COMMONPROGRAMFILES(X86)', 'COMMONPROGRAMW6432', 'COMPUTERNAME', 'C

OMSPEC', 'FP_NO_HOST_CHECK', 'HOMEDRIVE', 'HOMEPATH', 'NUMBER_OF_PROCESSORS', 'OS', 'PATH', 'PATHEXT', 'PROCESSOR_ARCHIT

ECTURE', 'PROCESSOR_IDENTIFIER', 'PROCESSOR_LEVEL', 'PROCESSOR_REVISION', 'PROGRAMDATA', 'PROGRAMFILES', 'PROGRAMFILES(X

86)', 'PROGRAMW6432', 'PROMPT', 'PSMODULEPATH', 'PUBLIC', 'SYSTEMDRIVE', 'SYSTEMROOT', 'TEMP', 'TERM', 'TMP', 'USERDOMAI

N', 'USERNAME', 'USERPROFILE', 'VS100COMNTOOLS', 'WINDIR', 'WINDOWS_TRACING_FLAGS', 'WINDOWS_TRACING_LOGFILE']

>>>

                                                     

>>> os.environ['TEMP']                                                                                                  

'C:\\Windows\\TEMP'


8、#使用for循环分割文件os.pathsep进行输出PYTHONPATH环境shell变量路径和使用sys.path输出合并变量路径

>>> import os                                                                                     

>>> os.environ['PYTHONPATH']                                                                      

'c:\\python'                                                          

>>> for srcdir in os.environ['PYTHONPATH'].split(os.pathsep):                                     

...     print(srcdir)                                                                             

...                                                                   

c:\python                                                    

>>> import sys                       

>>> sys.path[:3]                                                                                  

['', 'c:\\python', 'C:\\Program Files\\Python36\\python36.zip']  


9、#修改shell变量路径

>>> os.environ['TEMP']                                                

'C:\\Windows\\TEMP'                                            

>>> os.environ['TEMP']=r'c:\temp'                              

>>> os.environ['TEMP']                                                                            

'c:\\temp'          


10、#shell变量设置和读取,setenv.py代码如下:

#!/usr/bin/env python

import os

print('setenv...',end=' ')

print(os.environ['TEMP']) #this is shell var keys


os.environ['TEMP'] = 'Brian'     ​    ​#Run in the background os.putenv

os.system('python echoenv.py')


os.environ['TEMP'] = 'Arthur' #Pass update value

os.system('python echoenv.py') #Link c language library module


os.environ['TEMP'] = input('?')

print(os.popen('pythonechoenv.py').read())


输出结果:

c:\Windows\System32>python setenv.py                                                                                    

setenv... C:\Windows\TEMP

echoenv... Hello, Brian

echoenv... Hello, Arthur            

?Brian                              

echoenv... Hello, Brian


11、#修改shell变量值并使用echoenv.py输出值

c:\Windows\System32>set TEMP=Bob                                                                                        


c:\Windows\System32>python echoenv.py

echoenv... Hello, Bob


12、#标准流输出sys.stdin,sys.stdout,sys.stderr

>>> import sys

>>> for f in (sys.stdin,sys.stdout,sys.stderr):

...     print(f)                                                                                  

...                                                                                               

<_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>                                      

<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>                                     

<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'> 


13、#标准流输出例子:

>>> print('hello stdout world')                                                                   

hello stdout world                                                    

>>> sys.stdout.write('hello stdout world' + '\n')                                                                       

hello stdout world                                                                                                      

19                                                                                                                      

>>> input('hello stdin world>')                                                                                         

hello stdin world>spam                                                                                                  

'spam'                                                                                                                  

                                                              

>>> print('hello stdin world>'); sys.stdin.readline()[:-1]                                                              

hello stdin world>                                                                                                      

eggss                                                                                                                   

'eggss'      


14、#简单的读取,输出,打印的小程序        

teststreams.py代码如下:

#!/usr/bin/env python

"read numbers till eof and show squares"


def interact():

print('Hello stream world') #output data is sys.stdout

while True:

try:

reply = input('Enter a number>')     ​    ​#input is sys.stdin and data

except EOFError:

break #break is abnormal

else:

num = int(reply)

print("%d squared is %d" %(num,num ** 2)) #output is strings

print('Bye')


if __name__ == '__main__': #function is head

interact() #output is function


输出结果如下:

c:\python>python teststreams.py                                                                                    

Hello stream world

Enter a number>12

12 squared is 144              

Enter a number>10 

10 squared is 100              

Enter a number>^Z 

Bye     

注意:^Z 是键盘上的ctrl+z


15、#使用“<”将信息输入到input.txt文件中

创建input.txt 文件,文件内容是:

6

8

自动重定向输入打印数据

c:\python>python teststreams.py < input.txt  

Hello stream world                                                                                                 

Enter a number>8 squared is 64               

Enter a number>6 squared is 36             

Enter a number>Bye


16、# 自动重定向输入并输出数据

 c:\python>python teststreams.py < input.txt > output.txt

查看output.txt文件内容:

Hello stream world

Enter a number>8 squared is 64

Enter a number>6 squared is 36

Enter a number>Bye


17、#使用more管道输出数据

c:\python>python teststreams.py < input.txt | more

Hello stream world                                      

Enter a number>8 squared is 64

Enter a number>6 squared is 36               

Enter a number>Bye


18、# type函数查看数据内容

c:\python>type writer.py                                                                                                

#!/usr/bin/env python                                                                                                   

print("Help! Help! I'm being repressed!")                                                                               

print(42)


c:\python>type reader.py                                                                                                

#!/usr/bin/env python                                                                                                   

print('Got this: "%s"' % input())

import sys

data = sys.stdin.readline()[:-1]

print('The meaning of life is',data,int(data) * 2)                                                                      

c:\python>python writer.py                                                                                              

Help! Help! I'm being repressed!

42                              


c:\python>python writer.py | python reader.py                                                                           

Got this: "Help! Help! I'm being repressed!"                                                                            

The meaning of life is 42 84     

 

19、#sore排序脚本和 adder脚本演示:

sorter.py脚本代码:

#!/usr/bin/env python

import sys

lines = sys.stdin.readlines() #input is readlines sort

lines.sort()

for line in lines: #this is for loop output

print(line,end='')


adder.py脚本代码:

#!/usr/bin/env python

import sys

sum = 0

while True:

try:

line = input() #input is readlines() method

except EOFError: #abnormal is type

break #break is loop

else:

sum += int(line) #sting.atoi() method

print(sum) #print is sum


运行输出sorter.py脚本:

1、输出前先创建data数据文件

c:\python>type data.txt

123                                          

000                                         

456                         

231

789                                                                                                                     

346                                                                                                                     

2、运行脚本:

c:\python>python sorter.py < data.txt

000                                          

123                                         

231                         

346

456                                                                                                                     

789 


运行输出adder.py脚本进行data全部数据进行相加操作

c:\python>python adder.py < data.txt                                                                                    

1945

使用管道方式进行相加操作

c:\python>type data.txt | python adder.py                                                                               

1945


20、# 使用ype 函数查看writer2.py脚本内容,并进行sorter.py排序和相加操作

c:\python>type writer2.py

#!/usr/bin/env python                                                                                                   

for data in(123,0,999,42):                                                                                              

        print('%03d' %data)


c:\python>python writer2.py | python sorter.py

000                      

042                      

123                                                                                                                     

999  


c:\python>python writer2.py | python sorter.py | python adder.py

1164  








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

随行之旅

python国产化自动化

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值