我有一个使用python 3.4.3编写的python脚本,它会输入一个ip地址,用户名和密码的.csv文件,以传递给另一个批处理脚本.
import pdb
import csv
import os
import subprocess
import datetime
import time
import signal
from multiprocessing import Process
def callGetDimmBatchFile(logFile,batchFileName,ipAddress,userName,passWord):
print('\nId: {0}'.format(counter) + '\n',file=logFile,flush=True)
command ='{0} -i {1} -u {2} -p {3}'.format(batchFileName,passWord)
print(command,flush=True)
print("IP Address is {0}".format(ipAddress))
print("User name is {0}".format(userName))
print("Password is {0}".format(passWord))
timeout = 60
start = datetime.datetime.now()
process = subprocess.Popen(command,stdout=logFile,stderr=logFile)
while process.poll() is None:
time.sleep(0.1)
now = datetime.datetime.now()
if (now - start).seconds > timeout:
process.kill()
# os.kill(process.pid,signal.SIGKILL)
# os.waitpid(-1,os.Warning)
return None
rc = process.wait()
print('\nReturn Code:',rc,flush=True)
logFile = open('log.txt','w+')
batchFileName = 'getfoo.bat'
pathToCsv = 'autorun-input.csv'
print('Path to CSV is {0}'.format(pathToCsv))
counter = 0
with open(pathToCsv) as csvFile:
reader = csv.reader(csvFile,delimiter=',')
for row in reader:
ipAddress = row[0]
userName = row[1]
passWord = row[2]
p = Process(target=callGetDimmBatchFile,args=(logFile,passWord))
p.start()
p.join()
#callGetDimmBatchFile(logFile,passWord)
os.system("pause")
它读入的文件(autorun-input.csv)是这样的:
10.69.69.1,taclab,taclab
10.69.69.2,taclab
10.69.69.3,taclab
10.69.69.4,taclab
10.69.69.5,taclab
10.69.69.6,taclab
10.69.69.7,taclab
10.69.69.8,taclab
10.69.69.9,taclab
10.69.69.10,taclab
它不能在几台Windows 7机器上运行,错误是这样的:
C:\Users\Taclab\Desktop\DimmScript\Python-Project-9\Python-Project\DimmReport>python autorun.py
Path to CSV is autorun-input.csv
Traceback (most recent call last):
File "autorun.py",line 44,in
我不明白哪个参数不正确.看起来p.open会抛出异常.
最佳答案
这种类型的错误通常是通过传递subprocess.Popen没有可执行文件的命令引起的.例如:
原文链接:https://www.f2er.com/python/438393.htmlsubprocess.Popen(' -s') # notice the space at the beginning
subprocess.Popen(['','-s']) # this will cause the same error as well
检查你的日志(你在错误之前将变量’command’写入你的日志),看看它是否由于某种原因无效
如果它没问题那么我猜它必须是日志文件,因为父进程打开它.
事实上,如果我尝试在我的电脑上做同样的事情(我在python2.7上尝试过它)它引发了一个不同的错误,关于日志文件已经关闭.
尝试做类似的事情:
with open('tempLog{0}.log'.format(os.getpid(),'w+') as f:
subprocess.Popen(command,stdout=f,stderr=f)
看看这是否有效