如何通过在python中的另一个程序中激活来运行程序

时间:2017-01-13 00:07:08

标签: python

我对编程很新,我想知道是否通过命令运行不同的文件例如:

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.")

2 个答案:

答案 0 :(得分:0)

如果通过" Program"你的意思是功能,那么

    import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Facebook, NativeStorage } from 'ionic-native';
import { LoginPage } from '../login/login';

@Component({
  selector: 'page-user',
  templateUrl: 'user.html'
})

export class UserPage {

  user: any;
  userReady: boolean = false;

  constructor(public navCtrl: NavController) {}

  ionViewCanEnter(){
    let env = this;
    NativeStorage.getItem('user')
    .then(function (data){
      env.user = {
        name: data.name,
        gender: data.gender,
        picture: data.picture
      };
        env.userReady = true;
    }, function(error){
      console.log(error);
    });
  }

  doFbLogout(){
    var nav = this.navCtrl;
    Facebook.logout()
    .then(function(response) {
      //user logged out so we will remove him from the NativeStorage
      NativeStorage.remove('user');
      nav.push(LoginPage);
    }, function(error){
      console.log(error);
    });
  }
}

<小时/> 或者从另一个文件(在我的情况下为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 here 您的原始文件

main.py

答案 1 :(得分:0)

假设您有两个.py个文件:

  • script1.py:您想从此文件中调用另一个程序或Python脚本
  • script2.py:您要执行此文件

您现在有多种选择:

  1. 将其他文件视为模块(导入):script1.py中写:

    import script2(注意:文件必须位于同一目录中。)

  2. 产生一个shell进程:在script1.py中写:

    import os
    os.system('python /path/to/script2.py')
    
  3. 来自 call 模块
  4. 使用 subprocess :在script1.py中写:

    import subprocess
    subprocess.call(['python', '/path/to/script2.py'])
    
  5. 当调用&#39;时,选项1应该是首选的选项。另一个python文件。您可以用来运行非Python内容的其他内容,例如Bash命令:

    import subprocess
    subprocess.call(['ls'])