[英]How to pass arguments from one python script on the server to another?
I have 2 Python scripts on my server. 我的服务器上有2个Python脚本。 I want to run the second one, SendMail.py
, from MainScript.py
, and I need to pass 2 arguments to it. 我想从MainScript.py
运行第二个SendMail.py
,我需要传递2个参数。
I want to call send_mail
function in MainScript.py
: 我想在MainScript.py
调用send_mail
函数:
def send_mail(subject, body):
# call SendMail.py with and pass the subject & body arguments
so it will run SendMail.py
. 所以它将运行SendMail.py
。
How can I run the other script while passing the arguments? 如何在传递参数时运行其他脚本? Is it possible to do without importing the main function from SendMail.py
into MainScript.py
? 是否可以不将SendMail.py
的main函数导入MainScript.py
? How do I grab the arguments in SendMail.py
? 如何获取SendMail.py
的参数?
You can use the subprocess
module to run another python interpreter; 您可以使用subprocess
模块运行另一个python解释器; sys.executable
gives you a handy starting point: sys.executable
为您提供了一个方便的起点:
import subprocess
import sys
subprocess.call([sys.executable, 'SendMail.py', subject, body])
but best practice would be to just import SendMail
; 但最佳做法是只导入SendMail
; make sure you structure it to only run 'script-like' code with a if __name__ == '__main__'
guard, then import the main 'sending' function from SendMail
and re-use that: 确保你将它构造成仅运行带有if __name__ == '__main__'
保护的if __name__ == '__main__'
类似脚本”的代码,然后从SendMail
导入主“发送”功能并重新使用:
def send_mail(subject, body):
# main sending function
if __name__ == '__main__':
# parse command line arguments into subject and body
send_mail(subject, body)
then import SendMail
and call SendMail.send_mail(subject, body)
. 然后导入SendMail
并调用SendMail.send_mail(subject, body)
。
Use subprocess module: 使用子进程模块:
import subprocess
args = [subject, body]
subprocess.call(['python','SendMail.py'] + args)
Inside SendMail.py
use sys.argv
: 在SendMail.py
里面使用sys.argv
:
import sys
subject, body = sys.argv[1:]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.