[英]Calling a sub process after for loop is completed in python
I have python
script like below. 我有如下的python
脚本。 In this script, I am collecting stdout
and stderr
of the script in a file and storing in Linux
. 在此脚本中,我将脚本的stdout
和stderr
收集到一个文件中并存储在Linux
。
In this script, I am running the function path_finder
in a loop over input_file
In this script, I am using subprocess
to move data in Linux
to a different location. 在此脚本中,我在input_file
循环运行函数path_finder
在此脚本中,我正在使用subprocess
path_finder
将Linux
中的数据移动到其他位置。
I want this subprocess
call to run after finishing the loop
but instead, it runs when the loop
runs for the first time and when the second time the loop
runs it throws an error which is expected. 我希望此subprocess
调用在完成loop
后运行,但是当loop
第一次运行时,它将运行,而在第二次loop
运行时,它将引发预期的错误。 As the file is present it throws an error. 文件存在时,将引发错误。
#!/usr/bin/python
import os
import sys
import traceback
import subprocess
def path_finder(
table,
mysql_user,
user,
dir,
):
day = datetime.now().strftime('%Y-%m-%d')
month = datetime.now().strftime('%Y-%m')
Linux_path = '/data/logging/{}'.format(input_file)
New_path = '/user/{}/{}/logging/{}/{}/{}'.format(user,dir,mysql_user,month,day)
subprocess.call(["rm", Linux_path])
so = se = open('/data/logging/{}'.format(input_file), 'a',
0)
#re-open stdout without buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'a', 0)
# redirect stdout and stderr to the log file opened above
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
### CODE:
Do something
### if errors the print traceback
### repeat the same for every table in input file
## Execute below statement after for loop completed
subprocess.call(["cp", Linux_path, New_path])
if len(sys.argv) != 5:
print 'Invalid number of args......'
exit()
input_file = sys.argv[1]
mysql_user = sys.argv[2]
user = sys.argv[3]
dir = sys.argv[4]
input = open("{}.format(input_file)", "r")
for table in input:
path_finder(
table,
mysql_user,
user,
dir,
)
sc.stop()
print
How can I change my script so that the sub process
call will run after the for loop
is done? 如何更改脚本,以便在for loop
完成后运行sub process
?
I don't see what the problem is. 我看不出问题是什么。 The statement you want to execute last is currently present in the function 'path_finder' which is why it is running every time. 您最后要执行的语句当前存在于函数“ path_finder”中,这就是为什么它每次都在运行。 To make this run only once and after the for loop is finished, put the statement after it. 要使此操作仅运行一次,并且在for循环完成之后,请将语句放在它之后。
for table in input:
path_finder(
table,
mysql_user,
user,
dir,
)
subprocess.call(["cp", Linux_path, New_path])
This should do it. 这应该做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.