我对编程相当陌生,我想知道是否通过命令运行不同的文件,例如:
userInput = input("Hello, which game would you like to go to? Battleship, rock-paper-scissors, or Farkle?")
if userInput == "Battleship":
#runs Battleship.py
elif userInput == "rock-paper-scissors":
#runs RockPaperScissors.py
elif userInput == "Farkle":
#runs Farkle.py
else:
print("Sorry, I didn't understand that.")发布于 2017-01-13 00:34:11
假设您有两个.py文件:
script1.py:您想从这个文件中调用另一个程序或Pythonscript2.py:要执行的这个文件您现在有多个选项:
script1.py中写入:
import script2 (注意:文件必须位于同一个目录中)。script1.py中写:
导入os os.system('python /path/to/script2.py')call 从 subprocess 模块:In script1.py写:
导入子进程subprocess.call('python','/path/to/script2.py')在“调用”另一个python文件时,选项1应该是首选选项1。可以用来运行非Python内容的其他命令,例如Bash命令:
import subprocess
subprocess.call(['ls'])发布于 2017-01-13 00:15:57
如果你说的“程序”是函数,那么
def foo():
# Put your code here
userInput = input("Would you like to go to program 2? ")
if userInput == "yes":
foo()
或者来自另一个文件(在我的例子中是bar.py)
bar.py
def foo():
# Code heremain.py (原始文件)
userInput = input("Would you like to go to program 2? ")
if userInput == "yes":
bar.foo()https://stackoverflow.com/questions/41625283
复制相似问题