简体   繁体   English

如何使用另一个交付中的子进程运行python脚本

[英]How to run python script using subprocess from another delivery

I need to run another python script which generating data in my script I current working with. 我需要运行另一个python脚本,该脚本会在当前使用的脚本中生成数据。 I use subprocess to run it: 我使用subprocess来运行它:

cmd = 'python /home/usr/script.py arg1 arg2 arg3'
subprocess.Popen(cmd, shell=True)

But have a problem. 但是有问题。 Previous script generate few directories in 'current directory', it means in directory it was run in. And I can't modify previous script, cause it's not mine. 上一个脚本在“当前目录”中生成了几个目录,这意味着它在运行该目录中。而且我无法修改上一个脚本,因为它不是我的。 How to set current directory to dir where I want to get data? 如何将当前目录设置为要获取数据的目录? \\n
Another small problem is that when I run subprocess.Popen() my script doesn't end. 另一个小问题是,当我运行subprocess.Popen()脚本不会结束。 Should I run it in another way? 我应该以其他方式运行它吗?

the best way is to use subprocess.call instead (waits & terminates, Popen without the relevant wait() may create a zombie process) and use the cwd= parameter to specify current dir for the subprocess: 最好的方法是改用subprocess.call (等待并终止,没有相关的wait() Popen可能会创建一个僵尸进程),并使用cwd=参数为子进程指定当前目录:

cmd = ['python','/home/usr/script.py','arg1','arg2','arg3']
return_code = subprocess.call(cmd, cwd="/some/dir")

(also pass the command as a list, and drop shell=True , you don't need it here) (也将命令作为列表传递,并删除shell=True ,这里不需要它)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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