简体   繁体   English

通过命令行运行此python程序

[英]running this python program through the command line

I need to run this python program through my command line, but im not sure how to do so. 我需要通过命令行运行此python程序,但是我不确定如何执行此操作。 You're supposed to modify the PATH environment variables before you can do this, correct? 您应该先修改PATH环境变量,对吗? I'm using python 3.5 if that helps. 我正在使用python 3.5,如果有帮助。

from sys import argv

DEFAULT_KEY = 3

def main() :
   key = DEFAULT_KEY
   inFile = ""
   outFile = ""

   files = 0   # Number of command line arguments that are files.
   for i in range(1, len(argv)) :
      arg = argv[i]
      if arg[0] == "-" :
         # It is a command line option.
         option = arg[1]
         if option == "d" :
            key = -key
         else :
            usage()
            return

      else :
         # It is a file name
         files = files + 1
         if files == 1 :
            inFile = arg
         elif files == 2 :
            outFile = arg

   # There must be two files.
   if files != 2 :
      usage() 
      return 

   # Open the files.
   inputFile = open(inFile, "r")
   outputFile = open(outFile, "w")

   # Read the characters from the file.
   for line in inputFile :
      for char in line :
         newChar = encrypt(char, key)
         outputFile.write(newChar)

   # Close the files.
   inputFile.close()
   outputFile.close()

## Encrypts upper- and lowercase characters by shifting them according to a key.
#  @param ch the letter to be encrypted
#  @param key the encryption key
#  @return the encrypted letter      
#
def encrypt(ch, key) :
   LETTERS = 26   # Number of letters in the Roman alphabet.

   if ch >= "A" and ch <= "Z" :
      base = ord("A")
   elif ch >= "a" and ch <= "z" :
      base = ord("a")
   else :
      return ch    # Not a letter.

   offset = ord(ch) - base + key
   if offset > LETTERS :
      offset = offset - LETTERS
   elif offset < 0 :
      offset = offset + LETTERS 

   return chr(base + offset)

## Prints a message describing proper usage.
#
def usage() :
   print("Usage: python cipher.py [-d] infile outfile")

# Start the program.
main()

Have you tried ... 你有没有尝试过 ...

C:>python code.py arguments C:> python code.py 参数

Check this link to know about setting path variables if the above fails. 如果以上操作失败,请检查此链接以了解有关设置路径变量的信息。 How to add to the pythonpath in windows 7? 如何在Windows 7中添加到pythonpath中?

If you saved the program as cipher.py Run the program 如果您将该程序另存为cipher.py,请运行该程序

python cipher.py infile outfile.json

Check outfile.json is created... 检查outfile.json是否已创建...

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

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