从另一个python脚本运行一个python脚本?
我曾尝试每一件事情从从另一个python脚本运行一个python脚本?
if __name__ == "__main__":
到
os.system()
我已经通过在这里的所有其他类似的问题,看起来和阅读Python官方文档。
我不能得到这个
import os
ask1 = raw_input("Create bid? ")
create = "createbid.py %s" %()
def questions():
if ask1 == "yes":
os.system(create)
if ask1 == "no":
quit()
question()
可靠地运行ceatebid.py文件。我得到它与
if __name__ == "__main__":
但如果我也想调用另一个脚本?
我想根据问题的答案来调用不同的脚本。
使用os.system("python createbid.py")
的关键是传递字符串格式的shell命令。
如果您想与该脚本进行通信,您可能需要subprocess
。 查看此问题的答案:running bash commands in python
我不确定你想要做什么,但总的来说你应该可以做这样的事情。
import foo
import bar
ask = raw_input("Do something?")
if ask.lower() in ('yes', 'y'):
foo.do_something()
else:
bar.do_other()
这可能是因为在这里找到答案:What is the best way to call a Python script from another Python script?
所以,你需要在你createbid.py(和其他脚本)来定义一些方法:然后
def run()
print 'running'
在主脚本,
import createbid
def questions():
if ask1 == "yes":
createbid.run()
if ask1 == "no":
quit()
if __name__ == '__main__':
questions()
这个工作,当我用另一个脚本。我如何从多个其他脚本中进行选择? – mcmxl
您可以根据需要导入尽可能多的模块,完全如何@batman建议 –
或者,你可以使用exec
(Python2中的语句,Python3中的函数)。
假设您的脚本scriptA
存储在名为scriptA.py
的文件中。然后:
scriptContent = open("scriptA.py", 'r').read()
exec(scriptContent)
这样做的优点是,exec
允许你之前定义的变量,并使用这些脚本的内部。
所以,如果你在运行脚本之前定义一些参数,你仍然可以调用它们在你的解决方案:
#Main script
param1 = 12
param2 = 23
scriptContent = open("scriptA.py", 'r').read()
exec(scriptContent)
#scriptA.py
print(param1 + param2)
不过,这种做法更像是一个有趣的伎俩,并根据不同的情况,应该有几种方法可以做得更好。
感谢您的帮助!我结合了几个答案来使其工作。
这工作:
import seebid
import createbid
ask1 = raw_input("Create bid? ")
ask2 = raw_input("View bid? ")
create = createbid
see = seebid
def questions():
if ask1.lower() in ('yes', 'y'):
create.createbd()
elif ask1.lower() in ('no', 'n'):
ask2
if ask2.lower() in ('yes', 'y'):
see.seebd()
if __name__ == "__main__":
questions()
如今,启动其他程序的推荐方法是使用subprocess
模块。
这样做相对容易。这里是将它应用到你的问题,一个简单的办法:
import subprocess
import sys
create = [sys.executable, 'createbid.py']
def question(ans):
if ans == 'yes':
subprocess.call(create)
elif ans == 'no':
quit()
ask1 = raw_input('Create bid? ')
question(ask1)
print('done')
注意:当createbid.py
(或其他脚本)执行这种方法,__name__ == '__main__'
将是True
,不像这将是,如果它已被import
编辑。
https://docs.python.org/3/tutorial/modules.html – n1c9
你有没有尝试*** create =“python createbid.py%s”%()***而不是*** create = “createbid.py%s”%()*** – repzero
我试过了。两者都有相同的结果。 – mcmxl